#include #include using namespace std; class A { public: int _num; A() : _num(0) { cerr << "Constructing new A at " << this << endl; } A(int num) : _num(num) { cerr << "Constructing new A at " << this << endl; } A(const A &other) : _num(other._num) { cerr << "Copying A from " << &other << " to new A at " << this << endl; } ~A() { cerr << "Destroying A at " << this << endl; } A &operator=(const A &other) { if (this != &other) { cerr << "Changing value of _num in A at " << this << " from value at " << &other << endl; this->_num = other._num; } return *this; } }; A &changeGiven(A &obj, int newnum) { cerr << "Changing _num of " << &obj << endl; obj._num = newnum; return obj; } A copyAndChange(A &obj, int newnum) { cerr << "Copying and changing _num of " << &obj << endl; A newA(obj); newA._num = newnum; return newA; } void changeReference(A &obj, A &obj2) { obj = obj2; } void changePointer(A *obj, A *obj2) { obj = obj2; } void changeObject(A obj, A obj2) { obj = obj2; } int main(int argc, char *argv[]) { cerr << "Creating obj1" << endl; A obj1(42); cerr << endl; cerr << "Creating obj2" << endl; A obj2(23); cerr << endl; cerr << "Creating obj3 the hard way" << endl; A obj3; obj3 = A(5); cerr << endl; cerr << "Changing obj1" << endl; A &obj4 = changeGiven(obj1, 24); cerr << "Now obj1._num is " << obj1._num << endl; cerr << " ... and obj4._num is " << obj4._num << endl; cerr << " ... obj1 is at " << &obj1 << endl; cerr << " ... obj4 is at " << &obj4 << endl; cerr << endl; cerr << "Changing obj2" << endl; const A &obj5 = copyAndChange(obj2, 32); cerr << "Now obj2._num is " << obj2._num << endl; cerr << " ... and obj5._num is " << obj5._num << endl; cerr << " ... obj2 is at " << &obj2 << endl; cerr << " ... obj5 is at " << &obj5 << endl; cerr << endl; cerr << "Changing reference obj3 = obj1" << endl; changeReference(obj3, obj1); cerr << "Now obj3._num is " << obj3._num << endl; cerr << " ... and obj1._num is " << obj1._num << endl; cerr << " ... obj3 is at " << &obj3 << endl; cerr << " ... obj1 is at " << &obj1 << endl; cerr << endl; cerr << "Changing pointer obj3 = obj2" << endl; changePointer(&obj3, &obj2); cerr << "Now obj3._num is " << obj3._num << endl; cerr << " ... and obj2._num is " << obj2._num << endl; cerr << " ... obj3 is at " << &obj3 << endl; cerr << " ... obj2 is at " << &obj2 << endl; cerr << endl; cerr << "Changing object obj3 = obj1" << endl; changeObject(obj3, obj1); cerr << "Now obj3._num is " << obj3._num << endl; cerr << " ... and obj1._num is " << obj2._num << endl; cerr << " ... obj3 is at " << &obj3 << endl; cerr << " ... obj1 is at " << &obj2 << endl; cerr << endl; }