0

Given a Plain Old Data struct

struct Point
{
    int x;
    int y;
};

I can do

Point * p1 = new Point;   // members x, y uninitialised
Point * p2 = new Point(); // member x, y are 0

Now suppose I have

class PointAdv
{
    std::string sPrefix;
    int x;
    int y;
    std::string sPostfix;
};

and I do

Point * p1Adv = new PointAdv;
Point * p2Adv = new PointAdv();

Can I guarantee for the class in the 2nd expression, x and y are both 0 under any ISO C++ standard? Thanks

Also do any similar guarantees for PODs and classes hold for new[] (array new)?

Other StackOverflow questions are similar to this, but they do not make it clear what happens when the class is a mixture of class types and built-in types. I wish to know whether the builtin-types get zero initialised despite the presence of members that are class types when using new type();

SJHowe
  • 756
  • 5
  • 11
  • Retired Ninja: No, because it does not differentiate between a plain old data struct and a class. I know what happens with a plain old data struct. What I am interested in is what happens when the class is mixture of builtin types and non-builtin types. – SJHowe Jul 02 '21 at 19:29

1 Answers1

1

Yes, they will be zero-initialized.

POD-ness doesn't affect this. This happens because your class has an implicitly-generated default constructor (a constructor explicitly =defaulted in the class body would also do it).

This effect propagates recursively through classes that satisfy this criteria (so if you had any members of class types with default constructors satisfying this requirement, they would also be zeroed), and through arrays.

See cppreference for details.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207