Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re-initialize a struct's members

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 :(

like image 311
Mr. Boy Avatar asked Apr 02 '26 03:04

Mr. Boy


2 Answers

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

  • passing the structure members to the constructor & creating the structure object of it
  • overloading the =operator to do whatever you want
like image 117
Alok Save Avatar answered Apr 04 '26 15:04

Alok Save


You 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);
like image 21
Chris Avatar answered Apr 04 '26 17:04

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!