Inheritance question

As I compile and run this code, I get storage=3 and safe=5
I understand how storage is 3, but I don't know why safe is 5, instead of 3.
What is being carried over?

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 SuperA {
protected:
	int storage;
public:
	void put(int val) { storage = val; }
	int get(void) { return storage; }
};
class SuperB {
protected:
	int safe;
public:
	void insert(int val) { safe = val; }
	int takeout(void) { return safe; }
};
class Sub : public SuperA, public SuperB {
public:
	void print(void) { 
		cout << "storage = " << storage << endl; 
		cout << "safe    = " << safe << endl;
	}
};
int main(void) {
	Sub object;

	object.put(1);	object.insert(2);
	object.put(object.get() + object.takeout());
	object.insert(object.get() + object.takeout());
	object.print();
	return 0;
}
Last edited on
So let's walk through your code.
25
26
27
28
Sub object;

object.put(1); // storage = 1
object.insert(2); // safe = 2 

I'm sure that much you understand.

object.put(object.get() + object.takeout());
Since object.get() returns storage, which is 1, and object.takeout() returns safe, which is 2, that code becomes the same as
object.put(1 + 2); // So now storage = 3 .

Now, we get to
object.insert(object.get() + object.takeout());.
Now object.get() returns storage, but storage is now 3 (because of the last line).
object.takeout() is still 2 (since safe never got changed), so that call becomes
object.insert(3 + 2); // So now safe = 5 .
thank you so much!
Topic archived. No new replies allowed.