Invoking a virtual method from a base class method

I want to call an overridden method from a base class method called by a 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 Derived constructor calls the base function, which must call the overridden function "override()" from the derived class.

But this is not so. It calls Base :: override (). I understand why this function is called, but how can I implement my problem that the base function 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.

+4
source share
1 answer
  • Can you show us the code you use? The one you give must be completed in order to be compiled.

  • Upon completion, in the obvious way, I get the result that I expect: displaying the "derivative".

  • There is something connected that may be the problem you see, or it may be unrelated. At runtime of the constructor and destructor, the dynamic type is the same as the type of constructor / destructor. Therefore, if you have a basefunction call in Base () and not in Derived (), indeed, it is Base :: override, which is called, not Derived :: override. At run time, Base :: Base () does not have Derived members built, and it would be dangerous to call a member that could access them.

+3
source

Source: https://habr.com/ru/post/1392953/


All Articles