Within a C++ class hierarchy, is it possible to enforce a requirement that a particular virtual function always call its base class's implementation also? (Like the way constructors chain?)
I'm looking at a case where a deep class hierarchy has some common interface functions which each child overrides. I'd like each derived class' override to chain through to the base class. It's straightforward to do this explicitly with eg the code below, but there's the risk that someone implementing a new derived class might forget to chain through to the base.
Is there some pattern to enforce this, such that the compiler will throw an error if an override fails to chain the base?
So, in
class CAA
{
virtual void OnEvent( CEvent *e ) {
// do base implementation stuff;
}
}
class CBB : public CAA
{
typedef CAA BaseClass;
virtual void OnEvent( CEvent *e ) {
DoCustomCBBStuff();
BaseClass::OnEvent( e ); // chain to base
}
}
class CCC : public CBB
{
typedef CBB BaseClass;
virtual void OnEvent( CEvent *e ) {
Frobble();
Glorp();
BaseClass::OnEvent( e ); // chain to CBB which chains to CAA, etc
}
}
class CDD : public CCC
{
typedef CCC BaseClass;
virtual void OnEvent( CEvent *e ) {
Meep();
// oops! forgot to chain to base!
}
}
is there a way, some template trick or syntactic gimmick, to make CDD throw a more obvious error?
The way its done is the base class method is not virtual and calls a protected virtual method.
Of course, that only handles one level.
In your particular situation, a large amount of infrastructure can make it work, but it's not worth it.
The typical response is to add a comment
// Always call base class method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With