Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User-defined constructors and implicit default constructors

I have been reading this page to understand the concept of value-initialization http://en.cppreference.com/w/cpp/language/value_initialization

The effects of value initialization are:

  • If T is a class type with at least one user-provided constructor of any kind, the default constructor is called.

But this seems to be in direct contradiction with other sources explaining that if there is at least a user-defined constructor, then the compiler does not generate an implicit default constructor (expressions like "T t;" won't compile). Any explanation is welcome.

like image 909
usual me Avatar asked Oct 29 '25 05:10

usual me


1 Answers

"Default constructor" in this context means a constructor that can accept no arguments (either because it has no parameters or because it has only optional parameters).

"Implicit constructor" means a constructor generated for you automatically. This can be a no-args constructor, a copy constructor or (as of C++11) a move constructor.

So, there is no contradiction. When T is a class type with a user-provided constructor, then value initialization calls the default constructor. If this doesn't exist (because you defined another constructor but no no-args constructor), or if it is inaccessible (because you marked it private or protected and then used it from a place than cannot use such functions), then the value initialization is ill-formed and the compiler will reject your code. If it's declared but never defined then the program won't link.

Since C++11 the word "default" is probably somewhat ambiguous, since it's possible to define a copy constructor = default;

like image 64
Steve Jessop Avatar answered Oct 30 '25 18:10

Steve Jessop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!