Search code examples
c++c++03c++98

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


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.


Solution

  • 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.