Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When will compiler generate default constructor for a derived class

Tags:

c++

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?

like image 384
q0987 Avatar asked Aug 13 '11 23:08

q0987


2 Answers

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.

like image 58
Ernest Friedman-Hill Avatar answered Sep 20 '22 06:09

Ernest Friedman-Hill


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.
like image 32
Kerrek SB Avatar answered Sep 22 '22 06:09

Kerrek SB