Logic error

I came across this problem debugging a larger program and distilled it into the following little example.

I was expecting b.print() and a.print() to access the same b.state, and print the same "1", but the output says otherwise.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace 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?

Thank you.
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.
Last edited on
Thanks xismn. You read my mind.
The following example works as intended.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

class B
{
	private:
		int state = 0;
	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;
B &bRef = b;
A a(bRef);

int main()
{			// output:
	b.update(1);
	b.print();	// 1
	a.print();	// 1

	b.update(2);
	b.print();	// 2
	a.print();	// 2
}
Topic archived. No new replies allowed.