Take the 2-minute tour ×

I'm new to C++, and I'm now confused about the polymorphism concept and function pointers. It's kinda mixed up in my head.

In the code snipped below, I declare a function pointer that points to a method in BaseClass. Then I assigned it with &BaseClass::Print

The last two lines is the part i get confused: why these two lines doesn't yield the same result? I guess it's because the pointer myPtr points to the v-table, but i'm not sure. Also, if I want to make myPtr call the overridden BaseClass::Print() function, how could I do so?

Could anyone please clarify this to me? Thanks.

#include <iostream>
using namespace std;

class BaseClass{
        virtual void Print(){
            cout << "Hey!" << endl;

class DerivedClass : public BaseClass
        void Print(){
            cout << "Derived!" << endl;

int main()
    BaseClass *b = new DerivedClass;

    void (BaseClass::*myPtr)();

    myPtr = &BaseClass::Print;

    (b->*myPtr)(); //print "Derived!"
    b->BaseClass::Print(); //print "Hey!"
share|improve this question
A good read if you want to know a bit more about the nitty gritty of member function pointers: codeproject.com/Articles/7150/… –  Pete Feb 18 '13 at 22:37
Aside: Perhaps unintuitively, if print were to not be virtual, both would print "Hey!". –  Dynite Feb 18 '13 at 23:25
add comment

2 Answers

up vote 5 down vote accepted

The line (b->*myPtr)(); calls the BaseClass::Print member of b. BaseClass::Print is a virtual function and, since you're calling it through a pointer type, will be looked up polymorphically. That is, the correct function according to the dynamic type of b (which is DerivedClass) will be found.

The second line b->BaseClass::Print(); explicitly calls the Print member function that is a member of BaseClass. That's precisely what this syntax is for. It says "Hey, I don't care what the dynamic type of b is - I want you to call the BaseClass version."

share|improve this answer
this indeed clarify things. Thanks! –  pratchpak Feb 19 '13 at 6:08
add comment

Even though you created object of type DerivedClass it still has information about class from which it inherits, in that case - BaseClass. So when you are using:


You just ask to call Print() method from it's parent - BaseClass.

share|improve this answer
add comment

Your Answer


