q0987
q0987

Reputation: 35982

When will compiler generate default constructor for a derived class

Here is my observation:

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

// 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 any other cases that the compiler will not generated the default constructors for a derived class?

Upvotes: 7

Views: 2702

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477010

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

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

  • No const members.
  • No reference members.
  • All base classes must have accessible default constructors.
  • All non-static members must have accessible default constructors.

Upvotes: 5

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

The compiler won't generate a default constructor if the superclass has no default constructor. In other words, since the superclass constructor needs an argument, and the compiler can't be expected to know what an appropriate default value is, the compiler will fail to generate a useful default constructor. But if you added a no-argument constructor to ClassCBase, ClassC would be usable as-is.

Upvotes: 8

Related Questions