Value initialization


Something thats very new to me is the initialization of vars etc that are not 0 or null. I assume this is because c++ just allocates a memory slot without resetting its content.

My question is this, if i have a class or struct that has several vars in it, is there a quick way of zeroing all the values without having to do them all in the CTOR?
The constructor is there for that, if you don't like having several assignments or a long initializer lists you can do something like this:
var1 = var2 = var3 = 0;
so you assign 0 to every variable in a single line but you have to assign a value somewhere and initializer lists are the best places to do that
hmm, better than nothing i guess :)
thanks for the info.

Dont suppose you know if theres an automatic build constructor tool in codeblocks by chance (i have about 100 vars to reset :( )
There is array-style initialization of structs, but I don't recommend it...

For example:
1
2
3
4
5
6
struct Obj
{
    int a, b;
}
//...
Obj obj = {};


That should zero out obj.a and obj.b, but that syntax is not allowed for classes. Also, I have no idea what will happen if the members are not all numbers...

The constructor initialization list is the best way to go.
If you want default construction of POD types to initialize the variables, you can use boost::value_initialized<> template.

 
boost::value_initialized<int> x;  // x == 0 now 
I love it when you post boost stuff, jsmith. We don't use it where I work and I've been meaning to familiarize myself with it on my own...of course, I haven't gotten around to it... Right now I'm busy reading up on Qt.

My point is, keep it up; maybe someday I'll start remembering these things!
Topic archived. No new replies allowed.