Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
There are two classes which are not related say, Class1 and Class2.
I have some information in a variable in class 2 which has to be accessed in Class1.

When i create an object of Class2 to access the variable in my Class1 , the data in the variable is lost.

How can we achieve this ?

What I have tried:

I tried to create the object of class2 in my class1 to access the variable
Posted
Updated 30-Oct-16 22:18pm

When you create an instance of an object all data is new and empty. You must assign after creation.

C++
Class2 *obj2 = new Class2();
obj2->data = obj1->data;//assign some public data 


Try it out with the debugger. There is an area where you can see the content of the variables and members.
 
Share this answer
 
The usual method is to pass a pointer or reference.

Example:
C++
// Class1 header file

// Forward reference to Class2.
// Avoids including the header file of Class2.
class Class2;

class Class1 
{
    // ...
    void setFromClass2(const Class2& class2);
};

// Class1 source file
#include "class1.h"
#include "class2.h"

void Class1::setFromClass2(const Class2& class2)
{
    // Access members of class2 here
}

You may also create a member variable in Class1 that can be initialised with an instance of Class2. But then you must ensure that the Class2 object exists during the life time of Class1 or is reset and the code checks it:
C++
// Class1 header file

class Class2;

class Class1 
{
    // Initialise m_class2 to NULL in the constructor
    Class1() { m_class2 = NULL; }
    // ...
    void setClass2(const Class2 *class2) { m_class2 = class2; }
    void someFunc();
protected:
    const Class2 *m_class2;
};

// Class1 source file

void Class1::someFunc()
{
    if (m_class2)
    {
        // Access members of Class2 here when the pointer is not NULL
    }
}


The const keyword in my examples ensures that the content of Class2 can not be changed (read only).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900