Re: dynamic allocation and values of data members
subramanian100in@yahoo.com, India wrote:
Consider the following classes without ctors.
class Sample
{
private:
double d_val;
double* d_ptr;
};
class Test
{
private:
int i_val;
int* i_ptr;
Sample obj;
};
Suppose I allocate
Test* t = new Test();
Since I have mentioned 'new Test()' instead of just 'new Test',
will this statement set
t->i_val to zero, t->i_ptr to null pointer, t->obj.d_val to 0.0,
t->obj.d_ptr to null pointer ?
What does the standard say in this regard ?
The original C++ standard (C++98) says that the data members of your
object will remain uninitialized. Your object has a non-POD class type,
and in the original C++ standard the '()' initializer for such types
causes a constructor call. Since the constructors in your code do
absolutely nothing, the data will remain uninitialized. I.e. there's no
difference between doing 'new Test' or 'new Test()'.
Note, that it you declare all data members as 'public', the types will
become POD and '()' initializer will cause zero-initialization for all
data members, just like you describe.
The current C++ standard (post-TC1) is different in this regard though.
The '()' initializer causes the so called "value-initialization" being
applied to your object. And since your object has no user-declared
default constructor, in this case value-initialization will lead to
zero-initialization of all data-members.
--
Best regards,
Andrey Tarasevich