0

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?

2
  • Let me ask you, what is not explicit in Foo foo;? You have explicitly told the compiler the type you want to use and the name you want to give the object, so why would that not be explicit? Commented Feb 22, 2022 at 19:19
  • Failure to pick a suitable constructor doesn't leave a variable uninitialized, it causes a compilation error. Commented Feb 22, 2022 at 19:20

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.