I have a scenario where I need to access an object of a child class from another child class I have something like this: In parent.h
#include "child1.h"
#include "child2.h"
class Parent
{
public:
Child1 Child1_obj;
Child2 Child2_obj;
void setVar2_Value(int v2)
{
Child2_obj.Var2 = v2;
}
};
In child1.h
#include "child2.h"
class Child1
{
private:
int Var1;
public:
// these below functions are in .cpp file but I am placing here for simplicity to post
int DoArithmetic()
{
int temp1 = Increment_and_Multiply();
return temp1;
}
int Increment_and_Multiply()
{
Child2* pChild2; // How to initialize so I can access the value of the same object created inside Class A, insted of pointing to new Child2 object
// first increment Var2 and then multiply. I want this increment to be reflected in object created in class A
pChild2->Var2++;
return pChild2->Var2 * Var1;
}
};
In child2.h
#include "Child1.h"
class Child2
{
public:
int Var2;
};
In main.cpp
#include "parent.h"
int main()
{
Parent P1;
P1.setVar2_Value(5); // set Var2 value to 5
int res = P1.Child1_obj.DoArithmetic();
// Var2 value in now 6
// Do something else
}
As mentioned in the comments, I want Child2 class object access from Child1 so I can directly modify its values from Child1 which also get reflected in the object created in the parent class. Any guidance on this will be highly appreciated. Thank you.