Search code examples
c++classbindclass-method

Bind virtual class member function in base constructor


The example below shows a base class which binds a virtual member function to fn. On gcc 4.8, a call to fn on a derived class will call the overloaded calculate function. Can anyone explain why this happens? Is this behaviour compiler independend?

#include <functional>
#include <iostream>

class Base {
public:
    Base(){
        fn = std::bind(&Base::calculate,this,1);
    }

    virtual int calculate(int value){
        return value + 1;
    }

    std::function<int(int)> fn;  
};

class Derived : public Base {
public:
    Derived() : Base() {}

    int calculate(int value){
        return 0;
    }
};

int main(int argc, const char **argv){
    Derived test;
    std::cout << test.fn(10) << std::endl;
    /* Output of test.fn(10) is zero, so overloaded function was called */
    return 0;
}

Solution

  • The code behaves as expected: calling a virtual member function dispatches to the most-overridden function in the most-derived object that contains the instance object of the call. The fact that you're using a member function pointer (inside a bind expression) makes no difference; in fact, the whole point of pointers-to-member-function is that they work correctly with virtual dispatch.

    If you want a non-virtual call of the base function, you can do something like this:

    Base() : fn([this]() { return this->Base::calculate(1); }) {}