Home > Back-end >  Default initialization explicit constructor c
Default initialization explicit constructor c

Time:02-23

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?

CodePudding user response:

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
}
  • Related