Up until now, I've been using the old C way of sharing objects by passing pointers instead of references. But I've run into some trouble.
Here's a simplified case of what I'm trying to do:
#include <iostream>
class Test{
protected:
int a;
public:
Test() : a(0) {}
void change(int b) { a = b; }
int getA() { return a; }
};
class Obj{
protected:
Test test;
public:
Obj(Test& t) : test(t) {}
void check() {
test.change(5);
std::cout << "o.test.getA() = " << test.getA() << "\n";
}
};
int main(){
Test t;
Obj o(t);
t.change(4);
std::cout << "t.getA() = " << t.getA() << "\n";
o.check();
std::cout << "t.getA() = " << t.getA() << "\n";
return 0;
}
I'm trying to alter Test t defined in the main function through o, but the output shows that's not what's happening:
t.getA() = 4
o.test.getA() = 5
t.getA() = 4
I expected the last t.getA() to return 5. Did I so something wrong or am I misunderstanding what references are supposed to be used for, other than a replacement for sending pointers?