468,491 Members | 1,991 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,491 developers. It's quick & easy.

struct initialization

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

Jul 18 '06 #1
14 4457
seema wrote:
#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));

Jul 18 '06 #2

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>
should be:
#include <iostream>
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.
>
Some body please explain,
Seema Rao
Jul 18 '06 #3
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.
Salt_Peter 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>

should be:
#include <iostream>
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.

Some body please explain,
Seema Rao
Jul 18 '06 #4
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;
}
Jul 18 '06 #5
voidtwerp wrote:
seema wrote:
>#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));
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.
Jul 18 '06 #6
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).
--

Frederick Gotham
Jul 18 '06 #7
seema posted:

myclass(){}


Don't resort to messy, non-portable means. The following is fully-portable
and does exactly what you want:
myclass() : x() {}

--

Frederick Gotham
Jul 18 '06 #8
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
Jul 18 '06 #9
Hi

seema wrote:
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

Jul 18 '06 #10

Ron Natalie wrote:
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.

Jul 18 '06 #11
Victor Bazarov posted:

>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?)

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] = {};
--

Frederick Gotham
Jul 18 '06 #12
Frederick Gotham wrote:
Victor Bazarov posted:

>>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?)


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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 18 '06 #13
Victor Bazarov wrote:
>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...
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.
Jul 18 '06 #14
seema wrote:
No their is no way i can declare a constructor in the mystruct because


Please don't top-post. Your reply belongs following or interspersed
with properly trimmed quotes. See the newsgroup FAQ:
<http://www.parashift.com/c++-faq-lite/how-to-post.html#faq-5.4>


Brian
Jul 18 '06 #15

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by sathyashrayan | last post: by
10 posts views Thread by emma middlebrook | last post: by
6 posts views Thread by arnuld | last post: by
6 posts views Thread by Daniel Rudy | last post: by
2 posts views Thread by dj3vande | last post: by
10 posts views Thread by Juha Nieminen | last post: by
5 posts views Thread by ssylee | last post: by
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.