Gunter Solf
Gunter Solf

Reputation: 88

Calling a virtual method from a base class method

I want to call a overridden method from a base class method called by the derived class:

class Base {
    Base();
    virtual void function override() {}
    void basefunction() {
        override();
    }

class Derived : public Base {
    Derived() {
        basefunction();
    }
    virtual void function override() {
        cout << "derived" << endl;
    }
}

main() {
    Base* d = new Derived();
}

The constructor of Derived call the basefunction, which should call the overridden function "override()"from the derived class.

But it doesn't. It calls Base::override(). I understand why this function is called, but how can I implement my issue, that the basefunction calls the override function from the derived class?

If the override function is defined as pure virtual the declaration in the main function is not allowed.

Upvotes: 4

Views: 242

Answers (1)

AProgrammer
AProgrammer

Reputation: 52334

  • Is it possible to show us the code you are using? The one you give has to be completed in order to be compilable.

  • When completed in the obvious way, I get the result I expect: display of "derived".

  • There is something related which could be the problem you see, or it could be unrelated. During the execution of the constructor and the destructor, the dynamic type is the same as the type of the constructor/destructor. So if you have the call to basefunction in Base() instead of in Derived(), indeed it is Base::override which is called and not Derived::override. During the execution of Base::Base(), Derived's members have not been constructed yet and it would be dangerous to call a member which could access them.

Upvotes: 3

Related Questions