Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requiring overridden virtual functions to call base implementations

Tags:

c++

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?

like image 430
Crashworks Avatar asked Jan 03 '12 00:01

Crashworks


1 Answers

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
like image 160
Joshua Avatar answered Oct 26 '22 09:10

Joshua