In C ++, I can prevent the creation of a derived class by classes other than friends

In C ++, if I have an abstract base class, is it possible to prevent its derived classes created by classes other than friends who know the base class?

+5
source share
2 answers

You can define constructors as private, like any other function. For instance:

class foo { friend foo *FooConstructor(void); public: void Method(); void Method2(); private: foo(); foo(const &foo); }; foo *FooConstructor(void) { return new foo(); } 

This prevents foo from being created in any way, except for the FooContructor function.

+7
source

There are two ways you can have an inner class of a base class

First, to make the constructors private, for example:

 struct Sub1; struct Sub2; struct Base { virtual ~Base() = default; private: Base() = default; Base(const Base&) = default; friend struct Sub1; friend struct Sub2; }; struct Sub1 : protected Base {}; // ok, its a friend struct Sub2 : protected Base {}; // ok, its a friend struct Sub3 : protected Base {}; // compiler error 

The second way is to declare a base class in an anonymous namespace:

 namespace { struct Base{}; } struct Sub : Base {}; 

Now all classes in one translation unit can use Base , but other classes do not know that it exists.

This method is often less desirable since derived classes can be used as incomplete types (forwarded).

+2
source

All Articles