Click here to Skip to main content
15,893,663 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Lets say I have my main class declared in a header file, and defined in a cpp file.
classA.h
C++
#ifndef MAIN_H_
#define MAIN_H_

#include <iostream>

class ClassA
{
public:

     ClassA()
     {
     }

     ~ClassA()
     {
     }

     int i = 3
    
protected:

     void function(void);
};

#endif 



ClassA::function();

return 0;

Now let's say I have a 2nd class, ClassB.
Secondclass.h
C++
#ifndef HEADER_H_
#define HEADER_H_

#include <iostream>

class Secondclass
{
public:

     int ii = classAObj.i;  //i think this is wrong method
}


I just need to pass variables between classes(ClassA and ClassB). so i can access(display/update) the value of variable i from classB

Thanks for any help, I appreciate it.

What I have tried:

i tried what i mentioned above...
Posted
Updated 9-Mar-16 0:02am
Comments
Philippe Mori 9-Mar-16 12:28pm    
Learn the langage first! Read books or tutorials.

And usually you don't want to access variable in another class.

1 solution

you need an interface between the classes.
save a pointer of class b in class a and save a pointer of class a in class b if nessessary.
then you have access in both classes to the other class.


Example for classB with access to classA
class classB
{
public:
classB(classA *cA)
{
this->cA = cA;
}

void function()
{
this->cA->i = 5; // example
}

private:
classA *cA;
}
 
Share this answer
 
v3
Comments
XamBEE 9-Mar-16 6:44am    
would be nice if you add comments what you are doing each line. I didnt get it fully
Thanks for help, I appreciate it.
W Balboos, GHB 9-Mar-16 7:01am    
Any reason you cannot use inheritance and having class b inherit a public or protected member class a?

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