Search code examples
c++virtualfunction-pointersboost-bind

Calling base class definition of virtual member function with function pointer


I want to call the base class implementation of a virtual function using a member function pointer.

class Base {
public:
    virtual void func() { cout << "base" << endl; }
};

class Derived: public Base {
public:
    void func() { cout << "derived" << endl; }

    void callFunc()
    {
        void (Base::*fp)() = &Base::func;
        (this->*fp)(); // Derived::func will be called.
                       // In my application I store the pointer for later use,  
                       // so I can't simply do Base::func().
    }
};

In the code above the derived class implementation of func will be called from callFunc. Is there a way I can save a member function pointer that points to Base::func, or will I have to use using in some way?

In my actual application I use boost::bind to create a boost::function object in callFunc which I later use to call func from another part of my program. So if boost::bind or boost::function have some way of getting around this problem that would also help.


Solution

  • When you call a virtual method via a reference or a pointer you will always activate the virtual call mechanism that finds the most derived type.

    Your best bet is to add an alternative function that is not virtual.