Is it true that a default constructor is synthesized for every class that does not define one?

后端 未结 6 667
感情败类
感情败类 2020-12-28 11:09

If the class doesn\'t have the constructor, will the compiler make one default constructor for it ?

Programmers new to C++ often have two common misu

6条回答
  •  无人及你
    2020-12-28 11:27

    All the upvoted answers thus far seem to say approximately the same thing:

    A default constructor is synthesized for every class that does not have any user-defined constructor.

    which is a modification of the statement in the question, which means

    A default constructor is synthesized for every class that does not have a user-defined default constructor.

    The difference is important, but the statement is still wrong.

    A correct statement would be:

    A default constructor is synthesized for every class that does not have any user-defined constructor and for which all sub-objects are default-constructible in the context of the class.

    Here are some clear counter-examples to the first statement:

    struct NoDefaultConstructor
    {
         NoDefaultConstructor(int);
    };
    
    class Surprise1
    {
         NoDefaultConstructor m;
    } s1; // fails, no default constructor exists for Surprise1
    

    class Surprise1 has no user-defined constructors, but no default constructor is synthesized.

    It doesn't matter whether the subobject is a member or a base:

    class Surprise2 : public NoDefaultConstructor
    {
    } s2; // fails, no default constructor exists for Surprise2
    

    Even if all subobjects are default-constructible, the default constructor has to be accessible from the composite class:

    class NonPublicConstructor
    {
    protected:
        NonPublicConstructor();
    };
    
    class Surprise3
    {
        NonPublicConstructor m;
    } s3; // fails, no default constructor exists for Surprise3
    

提交回复
热议问题