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

后端 未结 6 658
感情败类
感情败类 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

    I think the misconception is:

    That a default constructor is synthesized for every class that does not define one

    That people think the default constructor, which accepts no arguments, will always be generated if you don't declare it yourself.

    However, this is not true, because if you declare any constructor yourself, the default one will not be automatically created.

    class MyClass {
    public:
        MyClass(int x) {}; // No default constructor will be generated now
    };
    

    This will lead to problems like when beginners expect to use MyClass like this:

    MyClass mc;
    

    Which won't work because there is no default constructor that accepts no args.

    edit as OP is still a little confused.

    Imagine that my MyClass above was this:

    class MyClass {
    };
    
    int main() {
        MyClass m;
    }
    

    That would compile, because the compiler will autogenerate the default constructor MyClass() because MyClass was used.

    Now take a look at this:

    #include 
    
    class MyClass {
    
    };
    
    int main() {
        std::cout << "exiting\n";
    }
    

    If this were the only code around, the compiler wouldn't even bother generating the default constructor, because MyClass is never used.

    Now this:

    #include 
    
    class MyClass {
    public:
        MyClass(int x = 5) { _x = x; }
        int _x;
    };
    
    int main() {
        MyClass m;
        std::cout << m._x;
    }
    

    The compiler doesn't generate default constructor MyClass(), because the class already has a constructor defined by me. This will work, and MyClass(int x = 5) works as your default constructor because it can accept no arguments, but it wasn't generated by the compiler.

    And finally, where beginners might run into a problem:

    class MyClass() {
    public:
        MyClass(int x) { _x = x; }
        int _x;
    };
    
    int main() {
        MyClass m;
    }
    

    The above will throw you an error during compilation, because MyClass m needs a default constructor (no arguments) to work, but you already declared a constructor that takes an int. The compiler will not generate a no-argument constructor in this situation either.

提交回复
热议问题