Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forbid using default constructor in derived classes, C++

Is there any way to create base class (such as boost::noncopyable) and inherit from it, which will forbid compiler to generate default constructor for derived classes, if it wasn't made by user (developer)?

Example:

class SuperDad {
XXX:
  SuperDad(); // = delete?
};

class Child : YYY SuperDad {
public:
  Child(int a) {...}
};

And result:

int main () {
  Child a;     // compile error
  Child b[7];  // compile error
  Child c(13); // OK
}
like image 391
Trollliar Avatar asked Aug 06 '15 18:08

Trollliar


People also ask

Can a derived class have a constructor with default parameters?

A derived class cannot have a constructor with default parameters. ____ 16. Default arguments can be used with an overloaded operator.

Can we override constructor in derived class?

Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. But, a constructor cannot be overridden.

Can we use constructor in derived class?

If we inherit a class from another class and create an object of the derived class, it is clear that the default constructor of the derived class will be invoked but before that the default constructor of all of the base classes will be invoke, i.e the order of invocation is that the base class's default constructor ...

Can default constructor be protected?

Typically, constructors have public accessibility so that code outside the class definition or inheritance hierarchy can create objects of the class. But you can also declare a constructor as protected or private . Constructors may be declared as inline , explicit , friend , or constexpr .


1 Answers

Make the constructor private.

protected:
    Base() = default;
like image 54
Trollliar Avatar answered Nov 06 '22 21:11

Trollliar