struct initialization

S

seema

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;
};

class myclass
{
mystruct x;
public:
myclass(){}
void display(){
cout <<"Hi guys ";
}
};

int main()
{
myclass me;
me.display();

}
If you debug this program in gdb and stop it in display() and see the
values of "x" they all contain some garbage values. I know we have to
intialize the values of struct in the constructor, to over come this
problem, we have to explicitly assign values to each and every
member of your structure like this,

myclass () { x.a=0;x.b=0;x.c=0;x.d=0;x.e=0;x.f=0;} But your code will
become messy when the members of the structure you have to intialize
are huge. Is their any way I can assign zero values to all of the
members of the structure at one shot? I mean any function that can be
used on Linux to do this initialization??

Some body please explain,
Seema Rao
 
V

voidtwerp

seema said:
#include <iostream.h>
struct mystruct
{
int a,b,c,d,e,f;
};
mystruct x;
are huge. Is their any way I can assign zero values to all of the
members of the structure at one shot? I mean any function that can be
used on Linux to do this initialization??

how about memset
memset((void*)&x,0,sizeof(mystruct));
 
S

Salt_Peter

seema said:
Hi all,
I am new to C++ programming. Can some body explain how to intialize the
structure values, consider this program,

#include <iostream.h>

should be:
#include said:
struct mystruct
{
int a,b,c,d,e,f;
};

Why not define a ctor here with an init list - change the initial
values to whatever you need:

struct MyStruct
{
int a,b,c,d,e,f;
MyStruct() : a(0), b(0), c(0), d(0), e(0), f(0) { }
~MyStruct() { }
};
class myclass
{
mystruct x;
public:
myclass(){}

myclass() : MyStruct() { }
~ myclass() { }
void display(){
cout <<"Hi guys ";
}

void display()
{
std::cout << "a = " << a << "\n";
std::cout << "b = " << b << "\n";
std::cout << "c = " << c << "\n";
std::cout << "d = " << d << "\n";
std::cout << "e = " << e << "\n";
std::cout << "f = " << f << std::endl;
}
};

int main()
{
myclass me;
me.display();

}
If you debug this program in gdb and stop it in display() and see the
values of "x" they all contain some garbage values. I know we have to
intialize the values of struct in the constructor, to over come this
problem, we have to explicitly assign values to each and every
member of your structure like this,

myclass () { x.a=0;x.b=0;x.c=0;x.d=0;x.e=0;x.f=0;} But your code will
become messy when the members of the structure you have to intialize
are huge. Is their any way I can assign zero values to all of the
members of the structure at one shot? I mean any function that can be
used on Linux to do this initialization??


This describes the need for default constructors. You could just as
well add parametized ctors in the examples above. You are not limited
to only provide a single ctor.
 
S

seema

No their is no way i can declare a constructor in the mystruct because
i mentioned
this structure just for illustration. But in real case the structure I
am using is from the
library, it's theora_info structure.
 
R

Ron Natalie

seema said:
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;
}
 
R

Ron Natalie

voidtwerp said:
how about memset
memset((void*)&x,0,sizeof(mystruct));
Memset is a lousy way of initializing pods. It will work for
ints, but if mystruct had pointers or reals in it, there's no
guarantee that writing zero bytes all over it is the same as
assigning zeros to it.
 
F

Frederick Gotham

voidtwerp posted:

memset((void*)&x,0,sizeof(mystruct));


This will only work for integer types.


Anyway, there's a better way of doing it (see else-thread).
 
F

Frederick Gotham

seema posted:

myclass(){}



Don't resort to messy, non-portable means. The following is fully-portable
and does exactly what you want:


myclass() : x() {}
 
V

Victor Bazarov

Ron said:
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).
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
 
M

Markus Moll

Hi
No their is no way i can declare a constructor in the mystruct because
i mentioned
this structure just for illustration. But in real case the structure I
am using is from the
library, it's theora_info structure.

Well, then use the Theora API:

| void theora_info_init(theora_info * c)
| Initialize a theora_info structure.
| All values within the given theora_info structure are initialized, and
| space is allocated within libtheora for internal codec setup data.

We're drifting off-topic...

Markus
 
N

Noah Roberts

Ron said:
Memset is a lousy way of initializing pods. It will work for
ints, but if mystruct had pointers or reals in it, there's no
guarantee that writing zero bytes all over it is the same as
assigning zeros to it.

That may be true theoretically but in practice I have never seen any
such implementation. Not that I've seen them all, but I've seen a few.
So for most that is a minor concern. More importantly though memset
doesn't work with non-pods and pods have a tendency to turn into
non-pods. That way you protect yourself against two cases: first, if
you ever add a copy op or virtual you don't have to go around switching
to this syntax; and second, if you ever decide a member needs a
different initial value than 0 you can build a default constructor and
not have to go around changing all your memsets. Finally, using the
construction syntax allows the compiler to do something else if it is
appropriate; you could end up with faster code and at worse no worse.

So, there are a few reasons not to use memset 0 but the theoretical
possibility of 0 not being 0 is not really a convincing one for most
people.
 
F

Frederick Gotham

Victor Bazarov posted:

The storage is actually _zero_-initialised, and no other initialisation
is performed (remember, C++ is stupidly inconsistent when it comes to
PODs?)


I think (and sincerely hope) that you're mistaken.

The following code should set the array of pointers to their null value,
and the array of doubles to their zero value (... shouldn't it?):

int main()
{
double static array1[8];

void static *array2[8];
}


This syntax shown above should be directly equivalent to the following (...
shoudn't it?):


double static array1[8] = {};

void static *array2[8] = {};
 
V

Victor Bazarov

Frederick said:
Victor Bazarov posted:

The storage is actually _zero_-initialised, and no other
initialisation is performed (remember, C++ is stupidly inconsistent
when it comes to PODs?)


I think (and sincerely hope) that you're mistaken.

The following code should set the array of pointers to their null
value, and the array of doubles to their zero value (... shouldn't
it?):

int main()
{
double static array1[8];

void static *array2[8];
}


This syntax shown above should be directly equivalent to the
following (... shoudn't it?):


double static array1[8] = {};

void static *array2[8] = {};

Yes, I've stated it incorrectly. Every static object is zero-initialised
(for pointers it means making them null, and for doubles making them 0.0)
at the start of the program (8.5/6).

V
 
R

Ron Natalie

Victor said:
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...

Nope, I've never bought that arugment. If unitialized data was
such a gosh-darn important speed feature, then some extra language
feature should be put in to support it. The big complaint was
that the speed would be degraded if you took unadulterated C
code and tried to cram that through a C++ compiler. I can tell
you as someone who moved about 800,000 lines of C code to C++
that is a entirely spurious argument.

I am however suffering from bugs where pods don't get initialized.
I'll take slightly slower over unpredictable and malfunctioning
everyday.
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").

Yes, but it because the defacto default initialization if other
initialization (static or dynamic) doesn follow along due to
explicit initializers.
...otherwise known as "value-initialisation"...

Don't get me started on freaking value-initialization. This idiotic
contraption was established to put bandaids on the "we don't always
initialize pods" concept.

C++ goes to great lengths to invent paradigms to describe that broken
C initialization rules coupled with the extensions for real
initialization (dynamic and consturctors and the like) that
C++ adds. It would have been so much easier to just initialize
everything and put warts on the syntax for the few times you don't
want initialization to take place.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top