The easiest way to achieve something like this would be to have something like the following:
class base {
virtual void time_impl()=0;
public:
void time() {
//Default behaviour
std::cout << "Hello\n";
//Call overridden behaviour
time_impl();
}
};
class child : public base {
void time_impl() override {
//Functionality
}
};
This way, when any child's time
function is called, it calls the base classes time function, which does the default behaviour, and then make the virtual
call 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 _impl
function 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