reference polymorphism

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 Base{
	public:
		int i=0;
		Base(int i) {this->i=i;}
		virtual ~Base() {}
		virtual void print(){
			cout<<"Base, i="<<i<<endl;
		}
};

class Derived:public Base{
	public:
		Derived(int i):Base(i){}		
		virtual ~Derived(){}
		virtual void 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:
1
2
3
4
        Base* rb1=new Base(1);
	rb1->print();
	rb1=new Derived(2);
	rb1->print();

gives output:

Base, i=1
Derived, i=2
Last edited on
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.
Last edited on
Thanks for the reply, so it copies from the Derived object only the part that "is related" to Base object?
Yes that's right. It will only copy the Base::i in this case.
Topic archived. No new replies allowed.