简体   繁体   中英

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-nothing 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM