I would like to extend a base class with a virtual function and keep the function name as virtual, but running code before and after the "possibly" overridden child function.
Here is an example:
I have a base class (interface) for things that can be drawn:
class IDraw {
public:
virtual void do_draw(Screen *scr) = 0;
};
I want to keep this interface in subclasses and be able to override it, for example I have a class for a Game, which cleans the screen, draw stuff and than flip the display buffer:
class Game : public IDraw {
public:
// Keep the interface
// This can be overridden by sub classes
virtual void do_draw(Screen *scr) = 0; // (1)
private:
// But override the base class so if s.b. calls
// do_draw from a IDraw pointer it executes this!
void IDraw::do_draw(Screen *scr) override; // (2)
};
// Implementation of (2)
void Game::IDraw::do_draw(Screen *scr) {
// Do stuff before like clear the screen
scr->clear();
// Call the method supplied by childs
this->do_draw(scr); // (1)
// Present the drawing
scr->present();
}
Since I have code before and after the function supplied by the child I cannot simply override keeping it virtual because the child must decide if calling Game::do_draw() // (2) before or after.
I know I can simply call the function (2) with a different name, but since I need many class doing this kind of stuff it will end with plenty of names for the same concept.
Is there any way to do this sort of thing in C++11?
Aucun commentaire:
Enregistrer un commentaire