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:
"named constructors"
Define all constructors of the base class
privateand provide named constructors (static,publicmethod which returns an object of that class).Drawbacks:
"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 bepublicvirtualinheritance) from a helper class (H). That helper class has only private constructors. It has afriendrelationship to the to-be restricted classB. As onlyBmay call the constructor ofH, further successors ofBcan 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:
Bin memory because of thevirtualinheritance. See here.