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()    }



Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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