Better way to initialize struct bools?
Sep 7, 2012 at 11:15pm Sep 7, 2012 at 11:15pm UTC
So say I have a struct:
1 2 3 4 5
struct MyStruct{
bool Member1,
Member2,
Member3;
};
The way I normally would initialize these is by using a constructor with an initializer. ie:
1 2 3 4 5
MyStruct::MyStruct():
Member1(false ),
Member2(false ),
Member3(false )
{}
However when I have a fairly large struct that I don't really know yet what it will consist of this can lead to some potential headaches if i forget to initialize a member.
Can I initialize these when they're declared or do something cool like:
1 2
MyStruct mStruct;
mStruct = false ;
Thanks!
Sep 7, 2012 at 11:27pm Sep 7, 2012 at 11:27pm UTC
If your compiler supports new features of C++ then you can write
1 2 3 4 5
struct MyStruct{
bool Member1 = false ,
Member2 = false ,
Member3 = false ;
};
As for this record
1 2
MyStruct mStruct;
mStruct = false ;
it is invalid.
Last edited on Sep 7, 2012 at 11:30pm Sep 7, 2012 at 11:30pm UTC
Sep 8, 2012 at 2:27am Sep 8, 2012 at 2:27am UTC
Sweet thanks that is what I was looking for.
I knew that was invalid as far as that example but I was just hoping there was some super obscure technique to make it work.
Thanks again!
Sep 8, 2012 at 3:39am Sep 8, 2012 at 3:39am UTC
1 2 3 4 5 6 7 8 9 10 11
struct my_struct
{
bool a ;
bool b ;
bool c ;
my_struct( bool f = true ) : a(f), b(f), c(f) {}
};
my_struct one = true ; // true, true, true
my_struct two = false ; // false, false, false
Sep 8, 2012 at 11:38am Sep 8, 2012 at 11:38am UTC
When I read "fairly large struct" I think near 100 member variables. If this is the case you really just have to bite the bullet and write the code correctly.
Topic archived. No new replies allowed.