Re: struct initialization
Ron Natalie wrote:
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.
I find this hypocritical, Ron. You're enjoying the speed of your C++
programs thanks to omitting the initialisations for PODs, and then keep
bitching about them. Of course, I can be wrong about the enjoyment
part...
Initializingmystruct elements can be done one of three ways:
If mystruct is statically allocated, it will be default (zero)
initialized for you.
Please don't confuse things here. Zero-initialisation of the storage
of static objects has nothing to do with "default initialisation". It
is not done because you didn't ask ("default"). It's done at the
program start for all of them independent of your actions, simply
because you made the objects static.
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:
....otherwise known as "value-initialisation"...
mystruct *fp = new mystruct();
Without the parens it is left unitialized. There's no way to do
other than default initialization in this case.
Copy-initialisation is possible, but you need a prototype object for
that (or a function returning the prototype object).
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.
Empty curly braces are also allowed, I believe. You can also
copy-initialise from a temporary:
mystruct foo = mystruct();
(which will be value-initialised in that case).
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:
"Properly" is a stretch here.
myclass() {
static mystruct init; // this is default initialized
The storage is actually _zero_-initialised, and no other initialisation
is performed (remember, C++ is stupidly inconsistent when it comes to
PODs?)
x = init;
}
It is actually better to have 'myclass'-wide static and _initialise_
the 'x' member by copying the 'init', instead of assigning it (FAQ):
class myclass {
static mystruct init;
mystruct x;
public:
myclass() : x(init) {}
};
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask