Prevent the use of the default constructor in derived classes, C ++

Is there a way to create a base class (for example, boost :: noncopyable ) and inherit it, which will prevent the compiler from generating a default constructor for derived classes if it was not made by the user (developer)?

Example:

class SuperDad { XXX: SuperDad(); // = delete? }; class Child : YYY SuperDad { public: Child(int a) {...} }; 

And the result:

 int main () { Child a; // compile error Child b[7]; // compile error Child c(13); // OK } 
+7
c ++ inheritance constructor default-constructor
source share
3 answers

Make the constructor private.

 protected: Base() = default; 
+6
source share
 #include <iostream> using namespace std; class InterfaceA { public: InterfaceA(std::string message) { std::cout << "Message from InterfaceA: " << message << std::endl; } private: InterfaceA() = delete; }; class MyClass: InterfaceA { public: MyClass(std::string msg) : InterfaceA(msg) { std::cout << "Message from MyClass: " << msg << std::endl; } }; int main() { MyClass c("Hello Stack Overflow"); return 0; } 
+4
source share

According to this article cppreference.com (which basically is a translation of the C ++ standard of the 12.1 section standard from a lawyer to a person):

If no custom type constructors (struct, class or union) are specified for the class, the compiler always declares the default constructor as an in-built public member of its class.

The only way to control the implicit definition of the Child constructor from SuperDad is to force the compiler to define it as deleted .

This can be done if the default constructor (or destructor) from SuperDad deleted, ambiguous, or inaccessible - but then you need to define another way to create a base class and use it implicitly from all child constructors.

+1
source share

All Articles