Re: struct initialization
seema wrote:
Hi all,
I am new to C++ programming. Can some body explain how to intialize the
structure values, consider this program,
#include <iostream.h>
struct mystruct
{
int a,b,c,d,e,f;
};
Unfortunately, one of the stupidest inconsistancies in C++ is
that default initialization does not always occur for PODs.
Initializingmystruct elements can be done one of three ways:
If mystruct is statically allocated, it will be default (zero)
initialized for you. Otherwise you can use the aggregate initializer:
mystruct foo = { 1,2,3,4,5,6 };
If mystruct is allocated via new, you can specifically request default
initialization:
mystruct *fp = new mystruct();
Without the parens it is left unitialized. There's no way to do other
than default initialization in this case.
If mystruct is allocated as a non-static local variable (stack) you
must aggregate initialize it explicitly if you care
mystruct foo = { 0 }; // remainder is also initialzed to 0
or as above.
myclass () { x.a=0;x.b=0;x.c=0;x.d=0;x.e=0;x.f=0;}
You could add a constructor to mystruct (but it would stop being
POD):
mystruct::mystruct() : a(0), b(0), c(0), d(0), e(0), f(0) { }
Another idea is to just assign a properly default initialized object:
myclass() {
static mystruct init; // this is default initialized
x = init;
}