1

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
Matt Ellis
  • 142
  • 9
  • 2
    You can't call a derived method from the constructor. The derived object doesn't exist yet. – tkausl May 11 '20 at 20:15

1 Answers1

1

This cannot be done. You can see the explanation in this post.

The object is constructed from base - up. The base class gets constructed first and then the members of the derived class extend / override the base class. So when the base constructor is running, the members of the derived class don't exist yet, so you cannot call them.

Not sure what you need this for, but you can just call the same method again from the derived class and you should see the output of both calls (from base and from derived).