Dowemo
0 0 0 0


Question:

class A {
public:
   A();
private:
   char a[5];
   int* ptr;
};
A::A() : a(0), ptr(0) { }

Is this right?


Best Answer:


The only sensible thing you can do with a C-array in C++03 is value-initialize it (in C++11 and beyond it can be list-initialized).

From the C++03 standard, §8.5/7:

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

And from §8.5/5:

To value-initialize an object of type T means:

  • if T is a class type with a user-declared constructor, then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
  • if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;
  • if T is an array type, then each element is value-initialized;
  • otherwise, the object is zero-initialized

To zero-initialize an object of type T means:

  • if T is a scalar type, the object is set to the value of 0 (zero) converted to T;
  • if T is a non-union class type, each nonstatic data member and each base-class subobject is zero-initialized;
  • if T is a union type, the object’s first named data member) is zero-initialized;
  • if T is an array type, each element is zero-initialized;
  • if T is a reference type, no initialization is performed.

So, if your constructor definition is changed to

A::A() : a(), ptr() { }

then you are guaranteed that post-construction, all 5 elements of A::a will have the value '' and A::ptr will be null.




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs