0

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");
}
  • What happens when you build (with extra warning enabled)? If it builds cleanly, then what happens when you run it? What do you expect to happen when building or running? What are the problems you're having? – Some programmer dude Jul 11 '23 at 07:08
  • Also please take some time to read [the help pages](http://stackoverflow.com/help), take the SO [tour], and read [ask]. Also please read [how to write the "perfect" question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/), especially its [checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Jul 11 '23 at 07:08

1 Answers1

2

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

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60