reference to virtual function

class drum :public instrument
class piano :public instrument 
    instrument i;
    piano p;
    drum d;
instrument &pi = i;

Here you make pi refer to the instrument object i.

pi = p;

Here you are assigning the piano object p to the object referred to by pi. It does not rebind the reference pi to refer to the piano object. It is still referring to an instrument object, just one that has been assigned to. The implicitly generated defaulted assignment operator will have been used, which, in this case, has no effect but would usually in the case of assigning a derived type to a base type result in object slicing.

So when you now call, the reference is still referring to an instrument object and instrument::play is executed.

So the point is, while you can get a pointer to point at a different object of a different type, you can’t do the same with a reference. It always points at the same object. You could fix your code by using multiple references:

instrument &pi = i;;// -

instrument &pp = p;;// pling

instrument &pd = d;;// dum, dum

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s