Question

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!

Was it helpful?

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;
};

OTHER TIPS

You're trying to prevent a derived class from overloading/overriding a method in the base. You can encourage it by marking methods as 'not overridable' (depending on the language), but there's always a way around it.

In other words, you can't force someone to use your class in a particular way, only tell them the way it should be used.

Answering for C++, you cannot have an inherited function "invisibly" called in the way you want.

The only methods that call down through inherited classes are constructors and destructors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top