When do we need to have a default constructor?

后端 未结 7 1368
终归单人心
终归单人心 2020-12-08 14:43

My question is simple. When do we need to have a default constructor? Please refer to the code below:

class Shape
{
    int k;

public:
    Shape(int n) : k         


        
7条回答
  •  忘掉有多难
    2020-12-08 15:06

    The compiler will define a default ctor if and only if you don't explicitly declare any ctors.

    Note that what's important is declaring the constructor, not necessarily defining it. It's fairly common, for example, to declare a private ctor, and never define it, to prevent the compiler from implicitly defining any others.

    Edit: Also note that C++11 has an =default syntax for dealing with situations like yours.

提交回复
热议问题