2

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.

cigien
  • 57,834
  • 11
  • 73
  • 112
user5534993
  • 518
  • 2
  • 17

1 Answers1

6

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.
user5534993
  • 518
  • 2
  • 17
  • Defining all destructors of the base class `private` does prevent to create objects of a derived class as long as they are automatically deleted. Which usually means that they must be created with `new` and `delete` is never called. – user5534993 Feb 09 '22 at 08:36