views:

325

answers:

3

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!

A: 

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.

hometoast
no - i want the method to be overwritten - but i want that the basefunction is called before the implementation in the derived class
Mat
+12  A: 

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;
};
shoosh
+1, I was just about to post that suggestion.
Roddy
If you make the virtual function protected (or even private) then you disable other code from calling the virtual method directly through a reference to base (not if they have a reference to a derived type, as the derived class can make the method publicly available)
David Rodríguez - dribeas
This serves my needs! thank you :)
Mat
A: 

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.

Roddy