reference or pointer

http://stackoverflow.com/questions/114180/pointer-vs-reference

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.

 

http://stackoverflow.com/questions/4364536/c-null-reference

reference must be initialized when used.

reference to virtual function

http://stackoverflow.com/questions/16135446/calling-virtual-functions-through-a-reference-to-the-base-class

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 pi.play(), 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;
pi.play();// -

instrument &pp = p;
pp.play();// pling

instrument &pd = d;
pd.play();// dum, dum

pointers to virtual funcitons

http://stackoverflow.com/questions/6754799/c-pointer-to-virtual-function

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

#include<iostream>
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()    }

Outputs:

Base::f()
Derived::f()