Call overridden method from base class

Viewed 73

How to call overridden bar method from base class in the following scenario?

There is requirement that callback should always call method foo which should call bar which is overridden by latest derived class.

#include <iostream>
#include <functional>
#include <typeinfo>

using namespace std;

std::function<void(void)> callback = nullptr;

class Base {
 public:
  Base(Base* ptr) { callback = std::bind(&Base::foo, *ptr); }

  virtual ~Base() {}

  virtual void foo() {
    bar();  // How call foo() from Derived instead of Base?
  }
  virtual void bar() { cout << "Base::bar" << endl; }
};

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

  virtual void bar() override { cout << "Derived::bar" << endl; }
};

int main() {
  cout << "Hello World" << endl;
  Base* b = new Derived();

  cout << "**callback**" << endl;
  callback();  // output should be 'Derived::bar'

  return 0;
}
2 Answers

You are binding the virtual method with the derived object improperly, slicing the derived object. Try this (* is removed)

Base(Base *ptr){
    callback = std::bind(&Base::foo, ptr);
}    

An alternative method that avoids std::bind() altogether:

Base(Base *ptr){
        callback = [this]() { foo(); };
    }

https://godbolt.org/z/pEs9ta

Note that this requires at least C++11.

Related