Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 406
Mat Avatar asked Dec 15 '09 19:12

Mat


1 Answers

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;
};
like image 128
shoosh Avatar answered Sep 25 '22 01:09

shoosh