It's easy to create and initialize a struct...
struct S{ int x; bool b; };
S s = {123,false};
But is it possible to use the same trick on an existing object? Or is this a 1-time only thing?
S s = {123,false};
s = {456,true}; //fails
s = S(){456,true}; //fails
Is there a syntax trick... obviously I could do:
S s = {123,false};
S temp={456,true};
s = temp;
But can I remove explicitly declaring the temp variable?
I should add I'm working on VC++ 2008, so no fancy modern C++ stuff is available :(
No. Initialization is a one time occurrence. Initialization occurs only when you create as well as assign some values to the created object at the same time (i.e., in one statement0.
Once the object is created you can only assign new values to it.
In short,
You can't reinitialise anything in C++. You can initialise objects or you can assign them.
Once you understand this fact, you can see that there are number of solutions possible such as
=operator to do whatever you wantYou could add a constructor to your struct and then you could do something like:
struct S
{
S(int x_in, bool b_in): x(x_in), b(b_in) { }
int x;
bool b;
}
S s(123, false);
s = S(456, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With