I have a class as defined below:
class A
{
int i;
char c;
int * iPtr;
};
Does the default constructor initialize the values of i, c & iPtr?
If so, what are the values that they each get initialized to?
thanks.
No.
Uli
There are two kinds of initialisation - default initialisation and
value initialisation.
Taking your example, if one defined an object as -
A DefaultInit;
- then the members of 'DefaultInit' are default initialised. Since
they are the basic types, the value each will have is undefined.
If instead, one defined an object as -
A ValueInit = A();
- then the members of 'ValueInit' are Value initialised, i.e., the
members will each be initialised to 0, '\0' and NULL respectively.
Since, as the class author, you want control how your members are
initialised irrespective of how the client users of your class create
objects, you would want to define your own constructor rather than let
the compiler synthesise one for you.
- Anand
no, the default ctor does no relevent initialization since whatever
values are already present are garbage values. Residual garbage if you
prefer. Unfortunately, some still beleive that to be valid
initialization.
In no way does that prevent you from taking on the honourable
responsability of providing your own def ctor:
class A
{
int i;
char c;
int * iPtr;
public:
A() : i(0), c('a'), iPtr(0) { }
~A() { }
};
That default ctor now initializes any default instance of A including
those found in a primitive container - which, by the way, require a
default ctor (compiler generated or not).
int main()
{
A array[10]; // all elements now have valid componants
}
That is, if you wrote the class as follows:
class A
{
int i;
char c;
int * iPtr;
public:
A(int n, char t, int* ptr) : i(n), c(t), iPtr(ptr) { }
~A() { }
};
..the compiler would be incapable of constructing the elements of the
array as is.
Anand saying that if I use in the follwoing way the values get
initialized.
A ValueInit = A();
- then the members of 'ValueInit' are Value initialised,
i.e., the
members will each be initialised to 0, '\0' and NULL
respectively.
I now double checked online FAQS and found that he is correct about
that....
when I just use "A a;" then object a does not get initialized. I think
you are explaining for this scenario.. right...
Thanks.