Archie Gertsman
Archie Gertsman

Reputation: 1661

C++ Struct Value Initialization

I was messing around with structs and noticed that of the following two examples, only one worked. Here they are:

struct Test
{ 
    char *name; 
    int age; 
}; 

Test p1 = { "hi", 5 };
//works


struct Test
{ 
    char *name; 
    int age; 
}p1; 

p1 = { "hi", 5 };
//error

How come the first one compiles and the second one doesn't? Isn't p1 an object of Test either way? Thanks.

Upvotes: 2

Views: 172

Answers (2)

John Zwinck
John Zwinck

Reputation: 249642

In the first example you are initializing a struct with two values in a "brace initialization." There is no support in C++ (or C) for assigning to a struct using a brace-enclosed list.

You could, however, create a new struct using brace initialization, then assign it to the old struct (p). C++ (and C) does support assignment of one struct to another of the same type.

For example, in C++11:

p1 = Test{ "hi", 5 };

Upvotes: 5

nimrodm
nimrodm

Reputation: 23849

The following does work with C++11: (Compile with g++ -std=c++11 init.cpp)

#include <iostream>

struct XXX {
    int a;
    const char *b;
};

int main() {
    XXX x;
    x = XXX{1, "abc"};
    // or later...
    x = XXX{2, "def"};

    std::cout << x.b << std::endl;

    return 0;
}

Upvotes: 2

Related Questions