#include <iostream>
usingnamespace std;
class B
{
private:
int state;
public:
void update(int newState) { state = newState; };
void print() { cout << state << endl; };
};
class A
{
private:
B b;
public:
A(B& b): b (b) {};
void print() { b.print(); };
};
B b;
A a(b);
int main()
{
b.update(1);
// output:
b.print(); // 1
a.print(); // 0 why do a.print() and b.print() not print the same state 1?
b.print(); // 1
}
output:
1
0
1
Why did a.print() and b.print() not print the same state 1?
I'm surprised that your compiler automatically initializes undefined variables to zero.
Why should they print the same state?
You instanciate an A object, and pass it b, whose state has not been explicitly initialized. a's member b gets set to global b, then you give global b a state.
My guess is that you thought that passing b by reference would somehow establish a relationship between the two objects(?).
*EDIT* this is nit-picky, but the semi-colons after your function bodies are not necessary.