c++oopstdvirtual-functionsstd-function

Calling base class method with std::function


I used std::function for basic class virtual method and had strange result. Then I call std::function object, derived (not basic) method is called. Please, can you tell me there is the problem?

#include <functional>
#include <iostream>
#include <string>

struct A
{
    virtual void username(const std::string& name)
    {
        std::cout << "A: username" << name << '\n';
    }

    A* A_ptr()
    {
        return this;
    }
};

struct B : public A
{
    void username(const std::string& name) override
    {
        std::function<void(const std::string&)> f = std::bind(&A::username, A::A_ptr(), std::placeholders::_1);
        wrapper(f, name);
    }

    void wrapper(const std::function<void(const std::string&)>& f, const std::string& s)
    {
        f(s);
    }
};

int main()
{
    B b;
    b.username("tname");
}

Solution

  • I don't think is is possible with std::bind, you can do it with a lambda though:

    std::function<void(const std::string&)> f = [this](const std::string& name) {
      A::username(name);
    };
    

    By default a member function pointer to a virtual method will use virtual dispatch, to call the base class method you need to use a different syntax which isn't possible though std::bind