Using C++98 (or C++03), how can a class (B
) be defined, such that no objects can be instantiated from a class (D
) deriving from B
.
struct B {};
struct D : public B {};
D d; // this should result in a compiler error
In C++11 (or newer) one could use the final
specifier.
I found these possible solutions, each with drawbacks:
Define all constructors of the base class private
and provide named constructors (static
, public
method which returns an object of that class).
Drawbacks:
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:
B
in memory because of the virtual
inheritance. See here.