开发者

Default constructors in C++

if i have constructors with parameters in my class, we need to provide a do-nothing constructor like :

1)

class A
{
  A(){};  //To satisfy the compiler
  //some constructors with parameter
};

just to satisfy the compiler.

Now if my class has a default parameter like :

2)

class A
{
//A(){} can't be used expilcilty or implicilty
A(int = 0);
};
A a;

There is going to be an ambiguity whether to call A::() or A::A(int = 0) so we cannnot provide any do-no开发者_运维问答thing constructor in the second case. So is it true that even the implicit constructor provided by the compiler gets suppresed in this case.

Please provide some clarification/thoughts.


A constructor with no parameters, or a constructor where all parameters have a default value, is the default construcor.

The compiler will not generate one if you have provided it.

You don't have to provide a default constructor if that doesn't make sense for your type. Of course that prohibits the use of your class in places where a default constructor is needed, but such use probably doesn't make sense either.


The compiler only generates a default ctor if you do not explicitly define one. So if you define a ctor, the compiler will not generate a ctor for the class.


If you need to explicitly disable the use of a constructor, you can make it private to the class.

Note that the compiler shouldn't be whinging about you not providing a constructor. The minute you provide one - and only one - it should automatically stop providing the default constructor

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜