开发者

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 : pub开发者_开发百科lic 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?


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.


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜