I have two classes where the first one is instantiated in an object wich is used inside another object of class 'two'. The problem I have is when trying to access the members of the object of first class through the object of second class.
I'm using this approach on arduino to instantiate an object wich controls a LCD with LiquidCrystal_I2C class wich needs parameters as soon is instantiated.
Example code:
#include <iostream>
using namespace std;
class A
{
public:
int data;
int state;
A (int); // Constructor needs parameter
void setState (int);
int getState ();
};
A::A (int newdata)
{
data = newdata;
}
void A::setState (int newstate)
{
state = newstate;
}
int A::getState ()
{
return state;
}
class B
{
public:
A * a;
int aState;
B ();
void attachA (int);
void printall ();
};
B::B ()
{
}
void B::attachA (int data)
{
A newobj (data);
a = &newobj;
a->setState (data + 1);
aState = a->getState ();
cout << "B obj. address?: " << this <<
", 'A' class obj. creation with data: " << data << " B.a->getState(): " <<
a->getState () << ", B.a->data: " << a->data << "\n";
}
void B::printall ()
{
cout << "B obj. address?: " << this << ", 'A' member class address?: " << a
<< ", B.aState: " << aState << ", B.a->getState(): " << a->
getState () << ", B.a->data: " << a->data << "\n";
}
int main ()
{
B temp_one;
temp_one.attachA (123);
B temp_two;
temp_two.attachA (345);
temp_one.printall ();
temp_two.printall ();
temp_one.printall ();
temp_one.a->setState (42);
temp_one.printall ();
return 0;
}
This prints:
B obj. address?: 0x7ffe088aa130, 'A' class obj. creation with data: 123 B.a->getState(): 124, B.a->data: 123
B obj. address?: 0x7ffe088aa140, 'A' class obj. creation with data: 345 B.a->getState(): 346, B.a->data: 345
B obj. address?: 0x7ffe088aa130, 'A' member class address?: 0x7ffe088aa108, B.aState: 124, B.a->getState(): 0, B.a->data: 4196144
B obj. address?: 0x7ffe088aa140, 'A' member class address?: 0x7ffe088aa108, B.aState: 346, B.a->getState(): 0, B.a->data: 4196144
B obj. address?: 0x7ffe088aa130, 'A' member class address?: 0x7ffe088aa108, B.aState: 124, B.a->getState(): 0, B.a->data: 4196144
B obj. address?: 0x7ffe088aa130, 'A' member class address?: 0x7ffe088aa108, B.aState: 124, B.a->getState(): 0, B.a->data: 4196144