Force a protected constructor in a class

Is there any mechanism that allows forcing the use of a protected constructor in the receiver class?

A simple example:

template<typename T> class Factory; class Base { template<typename T> friend class Factory; protected: Base(); }; class Child : public Base { public: Child(); // this should lead to a compile time error }; <template T> class Factory { Base* GetNew() { BOOST_STATIC_ASSERT(boost::is_base_of<Base, T>::value); Base* b = new T(); b->doStuff(); return b; } }; 

So, I want the Child class to only be created by the factory and ensure that all child classes that come from Base have a protected constructor.

+6
source share
2 answers

No, there is no way to provide this. In general, base classes are very limited in how they can restrict subclasses. Base not responsible and should not be responsible for protecting anyone who could write a class that inherits from Base .

+4
source

Short answer, no .

protected is the least useful access specifier since any derived class is free to publish the name (including the name of the constructor).

What you can do is use the pass key in the constructor to ensure that only the factory class creates the class.

 struct factory; // create_key constructor is private, but the factory is a friend. class create_key { create_key() {}; friend factory; }; struct only_from_factory { // base constructor demands a key is sent. Only a factory may create a key. only_from_factory(const create_key&) {}; }; 
+4
source

All Articles