When the compiler will generate a default constructor for the derived class

Here is my observation:

The compiler will NOT generate a default constructor for the derived class whose base class the constructor defined.

// example class ClassCBase { public: ClassCBase(int i) {} }; class ClassC : public ClassCBase { }; int main() { ClassC c; // error C2512: 'ClassC' : // no appropriate default constructor available } 

Q1> Do I understand correctly?

Q2> Are there other cases where the compiler does not generate default constructors for the derived class?

+7
source share
2 answers

The compiler will not generate a default constructor if the superclass does not have a default constructor. In other words, since the superclass constructor needs an argument, and the compiler cannot know what the corresponding default value is, the compiler will not be able to create a useful default constructor. But if you added a constructor with no arguments to ClassCBase , ClassC could be used as-is.

+8
source

The compiler will not define an implicit default constructor (and not just "declare", the definition is the key here) for a derived class if there is no default constructor for the base class. (Any constructor that can be called without arguments is the default constructor, regardless of the actual signature, if default arguments are provided).

So, we can summarize the requirements for any class to have a well-formed implicitly defined constructor:

  • There are no constant elements.
  • No reference elements.
  • All base classes must have accessible default constructors.
  • All non-static members must have accessible default constructors.
+5
source

All Articles