#include<iostream>
usingnamespace std;
class Base{
public:
int i=0;
Base(int i) {this->i=i;}
virtual ~Base() {}
virtualvoid print(){
cout<<"Base, i="<<i<<endl;
}
};
class Derived:public Base{
public:
Derived(int i):Base(i){}
virtual ~Derived(){}
virtualvoid print(){
cout<<"Derived, i="<<i<<endl;
}
};
int main(){
Base& rb1=*new Base(1);
rb1.print();
rb1=*new Derived(2);
rb1.print();// why Base::print() is called instead of Derived::print()?
Base& rb2=*new Derived(3);
rb2.print();
return 0;
}
Base, i=1
Base, i=2
Derived, i=3
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.