0

Possible Duplicate:
Looking for an easy way to reinitialize a struct

I dont actually know what my problem is called so I had not much luck searching for a solution.

I want to initialize a struct to an existing variable.

struct s { int i; };
s inst = { 7 }; // valid
inst = { 9 }; // invalid

How can I achieve something like this?

Community
  • 1
  • 1
Beta Carotin
  • 1,659
  • 1
  • 10
  • 27

2 Answers2

1

You can only intialize an instance once, by definition. Once an object is initialized, all you can do is change its state. In your example, assuming you want to change the state of object inst such that its data member holds the value 9, you can to assign to the 'i' data member of the s object:

inst.i = 9;

Another option is to assign a temporary s instance to yours. The temporary is constructed with its data member holding value 9:

inst = s{9};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • But I dont want to assign to the members of the instance of s that was first initialized. I want the old instance to be destructed and a new one to be constructed. – Beta Carotin Oct 14 '12 at 10:39
  • 1
    @BetaCarotin Well, you can't destruct the old instance. It will get destructed when it goes out of scope. All you can do after instantiating it is change it's state. – juanchopanza Oct 14 '12 at 11:01
  • @BetaCarotin I added an example on how to *assign* an `s` value to your instance. – juanchopanza Oct 14 '12 at 11:06
  • `s{9}` is called a compound literal. I wouldn't bet that an actual temporary is created. – bitmask Oct 14 '12 at 12:39
0

First, you can default-initialize your object and then assign to the member as such:

s inst;
inst.i = 7;

This isn't technically initialization though. If your struct has a user-defined constructor, you can use it to initialize your member. As such

struct s
{
    s(int i) :i(i) {}
    int i;
};

s inst(7);

However, if your struct is an aggregate(i.e. has no user-defined constructors, virtual functions, bases, or nonpublic nonstatic data members), you can initialize its members with braces. In your case s is an aggregate struct.

s inst = {7};

To read the full definition of aggregates and their usage, see this FAQ of mine

Community
  • 1
  • 1
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • As you can see in my code example, my struct indeed is an aggregate. I would like to know if there is a way to initilalize a struct in the way I described as invalid in my example. – Beta Carotin Oct 14 '12 at 10:44
  • @BetaCarotin: My first example is what you need, although it's ASSIGNMENT, not INITIALIZATION – Armen Tsirunyan Oct 14 '12 at 11:20