Question

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.

Was it helpful?

Solution

"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;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top