Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force deriving from a class virtually

We have a special framework for interfaces in our project, and part of the requirements is that classes which represent an interface may only be used as virtual base classes, not as non-virtual ones. Is there a way to enforce this in code? That is, produce a compilation error if the class is derived from non-virtually.

I have access to C++11 as implemented by VS 2010: this means static_assert, enable_if and <type_traits> are available.

like image 669
Angew is no longer proud of SO Avatar asked May 09 '13 07:05

Angew is no longer proud of SO


1 Answers

IMO, there is no clean and platform independent solution available to this problem.

The best way is to manually go and change each and every inheritance to virtual inheritance.
To accomplish that, identifying the derived classes of your interface (say class Base) is easy(!). Below steps can be followed for that:

  1. Make class Base as final (c++11); i.e. class Base final { ...
  2. Compile the code, it will generate compiler error for all its derived classes
  3. Go and check every derived class and make the inheritance as virtual
  4. Remove the final keyword and compile the code successfully

This process (unfortunately) has to be followed periodically, whenever you want to do such sanity checking.

like image 157
iammilind Avatar answered Nov 02 '22 06:11

iammilind