0

Say I have :

class Foo
{
public:
  int x;
  Foo() : x() {}
} 

Would it be UB to read x after the constructor has ran? More specifically, what type of initialization is this, zero, direct or default initialization?

I know if instead we'd have:

Foo() : x(42) {}

x would be direct-initialized to 42 but I'm not so sure for the snippet above and I don't want to get bit by the UB wolf if this turns out to be default-initialized.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
  • https://en.cppreference.com/w/cpp/language/value_initialization – Deduplicator Jul 08 '21 at 14:55
  • Isn't it a [zero-initialization](https://en.cppreference.com/w/cpp/language/zero_initialization) "*As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of elements of aggregates for which no initializers are provided."* and *"If T is a scalar type, the object's initial value is the integral constant zero explicitly converted to T."*? – Bob__ Jul 08 '21 at 14:57
  • @NathanOliver Thanks for the duplicate, no clue why I didn't find one. – Hatted Rooster Jul 08 '21 at 15:02
  • @HattedRooster No problem. FWIW, I googled *what do empty parentheses mean in member initializer c++* to find it. Target was the first result. – NathanOliver Jul 08 '21 at 15:03

1 Answers1

3

what type of initialization is this

x() performs value-initialization:

when a non-static data member or a base class is initialized using a member initializer with an empty pair of parentheses or braces (since C++11);

As non-class type int, x is zero-initialized as 0 at last.

  1. otherwise, the object is zero-initialized.
songyuanyao
  • 169,198
  • 16
  • 310
  • 405