Re: dynamic allocation and values of data members
"subramanian100in@yahoo.com, India" <subramanian100in@yahoo.com> writes:
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 ?
I just asked this question to my local C++ guru this morning, and he
said that no, these members are not implicitely initialized. You have
to do it yourself. The problem is that "[p]rimitive type member
variable like int, float etc does not have any constructors, so they
are just initialized with an undefined initial value which is often a
garbage."
Note that you should probably always define a constructor (perhaps
private), to let other objects use your class for its member and have
it automatically initialized with default values.
--
__Pascal Bourguignon__