A very similar question was asked here: C++: Overriding a protected method which is called by another method
However, I would like to know how to override a callback function in a Base class so that another method can call the derived class's callback from the constructor rather than the Base class's callback.
I've given an example below:
#include <iostream>
class Base {
protected:
virtual void callback() {
std::cout << "Base" << std::endl;
}
public:
Base() {
callback();
}
};
class Derived : Base {
protected:
void callback() override {
std::cout << "Derived" << std::endl;
}
public:
// Use Base's constructor to call print
Derived() : Base() { }
};
int main() {
Base B;
Derived D;
return 0;
}
The output is:
Base
Base
but I would like the output to be:
Base
Derived