How can I set up my class so it can't be inherited from in C++98/C++03?

I found these possible solutions, each with drawbacks:

"named constructors"

Define all constructors of the base class private and provide named constructors (static, public method which returns an object of that class).

Drawbacks:

  • Using that class is "not-so-clean" / less straightforward. The purpose of the effort should be to simplify using that class. The result requires more effort for using such classes.

"virtual inheritance trick"

I found this suggestion here and from Bjarne Stroustrup here. See also his book "The Design and Evolution of C++" sec 11.4.3.

The class for which inheritance shall be restricted (B), inherits (must be public virtual inheritance) from a helper class (H). That helper class has only private constructors. It has a friend relationship to the to-be restricted class B. As only B may call the constructor of H, further successors of B can not be instantiated.

In contrast to the "named constructors" solutions the "usual" constructor can be called. I consider this more straightforward for using that class.

Drawbacks:

  • Usually this will increase the size of objects of B in memory because of the virtual inheritance. See here.
  • It requires more effort for programming such classes.