Shouldn't line 28 call the print() method of a Derived object? Could someone explain to me what is happening and why the same example written with pointers instead of references works as I would expect, meaning something like:
No the equivalent code written with pointer would look like:
1 2 3 4
Base* rb1 = new Base(1);
rb1->print();
*rb1 = *new Derived(2); // Note that this doesn't change the pointer
rb1->print();
It is not possible to change the object that a reference is referring to. Line 27 is using the copy assignment operator (Base::operator=) to assign to the object being referred to by rb1. rb1 will still be referring to the same object as it was initialized to on line 25.