Possible Duplicate:
pure virtual function with implementation
I have a base class which has a function called time().
My idea is to have a pure virtual function which all the classes that inherits from it must implement.
However I also want to add the default behavior; Whoever calls time() function needs to print “hello”.
Is that possible?
The easiest way to achieve something like this would be to have something like the following:
This way, when any child’s
timefunction is called, it calls the base classes time function, which does the default behaviour, and then make thevirtualcall to the overridden behaviour.EDIT:
As Als says in the comments, this is called the Template method pattern which you can read about here:
http://en.wikipedia.org/wiki/Template_method_pattern
Althought for C++ that is a rather confusing name (as templates are something else, and “methods” don’t mean anything in C++ (rather
member function).EDIT:
Someone commented about the use of override, this is a C++11 feature, if you have it USE IT, it will save many headaches in the long run:
http://en.wikipedia.org/wiki/C%2B%2B11#Explicit_overrides_and_final
And also, the
_implfunction should be private, UNLESS you want the user to be to bypass the default behaviour, but I would argue that’s a poor design in most use-cases.Working test case
http://ideone.com/eZBpyX