reference or pointer

My rule of thumb is:

Use pointers if you want to do arithmetic with them or if you ever have to pass a NULL-pointer.

Use references otherwise.

reference must be initialized when used.

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

pointers to virtual funcitons

Pointers to members take into account the virtuality of the functions they point at. For example:

struct Base {
virtualvoid f(){ std::cout <<"Base::f()"<< std::endl;}
struct Derived:Base {
virtualvoid f(){ std::cout <<"Derived::f()"<< std::endl;}
void SomeMethod(Base& object,void(Base::*ptr)()){(object.*ptr)();}

int main(){
Base b;
Derived d;
Base* p =&b;
SomeMethod(*p,&Base::f);//calls Base::f()
p =&d;
SomeMethod(*p,&Base::f);//calls Derived::f()    }