Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Class Problem?

Class Problem?

Scheduled Pinned Locked Moved C / C++ / MFC
c++helpquestion
2 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • W Offline
    W Offline
    wow9999
    wrote on last edited by
    #1

    //A.h Class A { A(int i, int j); int GetIJ(); int K,L; } //A.cpp { A::A(int i, int j) { K=i; L=j; } A::GetIJ() { int M=K+L; return M; } } //B.cpp A *ATemp; { void B::FirstFunction() { int a=5; int b=6; A aTest(a,b); //Create a A Instance "aTest" ATemp=&aTest; //assign aTest to ATemp } void B::SecondFunction() { int XYZ=ATemp->GetIJ(); //Is this correct? If this is wrong please tell me why } } ************** Can I Create a Object in one function and using the object at another function?

    S 1 Reply Last reply
    0
    • W wow9999

      //A.h Class A { A(int i, int j); int GetIJ(); int K,L; } //A.cpp { A::A(int i, int j) { K=i; L=j; } A::GetIJ() { int M=K+L; return M; } } //B.cpp A *ATemp; { void B::FirstFunction() { int a=5; int b=6; A aTest(a,b); //Create a A Instance "aTest" ATemp=&aTest; //assign aTest to ATemp } void B::SecondFunction() { int XYZ=ATemp->GetIJ(); //Is this correct? If this is wrong please tell me why } } ************** Can I Create a Object in one function and using the object at another function?

      S Offline
      S Offline
      souldog
      wrote on last edited by
      #2

      Not this way. You have created the object on the stack in the first function and so the object is destroyed when the function returns. Therefore, your pointer to this object is no longer valid outside the scope of the first function. There are lots of ways to approach this problem, but one is to return an object of type A by value from the first function and assign it to another object of type A which is declared outside the function. The best method depends on the cost of creating and assigning the object.

      1 Reply Last reply
      0
      Reply
      • Reply as topic
      Log in to reply
      • Oldest to Newest
      • Newest to Oldest
      • Most Votes


      • Login

      • Don't have an account? Register

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • World
      • Users
      • Groups