4
struct A1
{
    int n;        
};

struct A2
{
    int n;
    A2(){}        
};

struct A3
{
    int n;
    A3() = default;        
};

Question 1:

Does the C++ standard guarantee the classes A1, A2, A3 are completely equivalent to each other?

Question 2:

A1 a1;
A2 a2;
A3 a3;

Will the compiler not zero-initialize a1.n, a2.n, a3.n as per the C++ standard?

xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • 2
    Not sure what you mean by that.. they're not equal since e.g. the first is an aggregate while the second isn't – Marco A. Nov 24 '16 at 08:15

2 Answers2

2

There's one difference that A1 and A3 are aggregate type, while A2 is not, because it has a user-defined constructor.

class type (typically, struct or union), that has

  • ...
  • no user-provided, inherited, or explicit (since C++17) constructors (explicitly defaulted or deleted constructors are allowed) (since C++11)
  • ...

It means for A1 and A3 they could be aggregate initialized, while A2 can't.

A1 a1{99}; // fine;  n is initialized to 99
A3 a3{99}; // fine;  n is initialized to 99
A2 a2{99}; // error; no matching constructor taking int found

Will the compiler not zero-initialize a1.n, a2.n, a3.n as per the C++ standard?

According to the rule of default initialization, if they're of automatic storage duration, no zero-initialization here, all values will be indeterminate. On the other hand, static and thread-local objects get zero initialized.

Community
  • 1
  • 1
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
2

They're not equal since they are different entities and have different initializations: the first and last one are aggregates, the second isn't

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

Read more about this here: What are Aggregates and PODs and how/why are they special?

So aggregate initialization works for A1 and A3, it doesn't for A2

struct A1
{
    int n;        
};

struct A2
{
    int n;
    A2(){}        
};

struct A3
{
    int n;
    A3() = default;        
};


int main()
{
   A1 obj1{42};
   //A2 obj2{42}; // error
   A3 obj3{42};


   return 0;
}

A1 a1; A2 a2; A3 a3;

Will the compiler not zero-initialize a1.n, a2.n, a3.n as per the C++ standard

The variables will be default initialized.

Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246