Search code examples
c++inheritancevirtualoverwritebase-class

Force derived class to call base function


If I derive a class from another one and overwrite a function, I can call the base function by calling Base::myFunction() inside the implementation of myFunc in the derived class.

However- is there a way to define in my Base class that the base function is called in any case, also without having it called explicitly in the overwritten function? (either before or after the derived function executed)

Or even better, if I have a virtual function in my virtual Base class, and two implemented private functions before() and after(), is it possible to define in the Base class that before and after the function in any derived class of this Base class is called, before() and after() will be called?

Thanks!


Solution

  • No, this is not possible.
    But you can simulate it by calling a different virtual function like so:

    class Base
    {
    public:
      void myFunc()
      {
        before();
        doMyFunc();
        after();
      }
    
      virtual void doMyFunc() = 0;
    };