C ++ how to call a method in a derived class from a base class

What I want to do is execute Execute() to start and end the call to Base::Done() , and then call Derived::Done() . I do this because the Base class Execute will do something, and when it is done, call Derived::Done() . I hope I explain it correctly. A kind of listener that gets called when the task is complete. I kind of went into cycles on how the Base class would call the Derived class.

 class Base { virtual void Done(int code){}; void Execute(); } void Base::Execute() { } class Derived : Base { void Done(int code); void Run(); } Derived::Done(int code) { } void Derived::Run() { Execute(); } 
+6
source share
2 answers

You can use the template method:

 class Base { public: void Execute() { BaseDone(42); DoDone(42); } private: void BaseDone(int code){}; virtual void DoDone(int) = 0; }; class Derived : Base { public: void Run() { Execute(); } private: void DoDone(int code) { .... } }; 

Here Base defines how its own and derived methods are used in Execute() , and derived types need to implement one component of this implementation through the private virtual DoDone() method.

+8
source

A base class method can simply call a derived method:

 void Base::Execute() { Done(42); } 

For the base class Done () to call before the derived class, you can name it as the first operator of the derived class method or use a non-virtual idiom.

Here's an example of calling it at the top of a derived class method. It depends on the derived class to understand it.

 void Derived::Done(int code) { Base::Done(code); } 

Here is an example of using a non-virtual idiom:

 class Base { void Done(int code){ // Do whatever DoneImpl(); // Do derived work. } virtual void DoneImpl() { }; ... }; class Derived { virtual void DoneImpl() { // Do derived class work. }; ... }; 
+3
source

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


All Articles