Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Default initialization explicit constructor c++

How does default initialization work in C++11 if the default constructor is explicit? For example:

#include <iostream>

struct Foo {
  int x;

  explicit Foo(int y = 7) : x{y} {}
}

int main() {
  Foo foo;
  std::cout << foo.x << std::endl;
}

In main, the variable foo is default initialized. Based on my understanding, this will call a default constructor, if one exists. Otherwise, no initialization occurs, foo contains indeterminate values, and printing foo.x is undefined behavior.

There is a default constructor for Foo, but it is explicit. Is that constructor guaranteed to be called, or is the last line of the program undefined behavior?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your use is okay. The worst thing that could happen would be that the compiler would not be able to use the constructor since it is explicit and fail to compile. However, defining a variable as you have will correctly call the explicit default constructor.

The use of explicit for a default constructor prevents uses like the following:

Foo some_fn() {
  return {}; // Fails as the default constructor is explicit.
  return Foo{}; // OK
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading