52

I have the following struct in my C++ code (I am using Visual Studio 2010):

struct mydata
{
    string scientist;
    double value;
};

What I would like to do is to be able to initialize them in a quick way, similar to array initialization in C99 or class initialization in C#, something á la:

mydata data[] = { { scientist = "Archimedes", value = 2.12 }, 
                  { scientist = "Vitruvius", value = 4.49 } } ;

If this is not possible in C++ for an array of structs, can I do it for an array of objects? In other words, the underlying data type for an array isn't that important, it is important that I have an array, not a list, and that I can write initializers this way.

2
  • 1
    There is no reason why it shouldn't work... (btw that would be .scientist = ...) Have you tried? Commented Dec 16, 2011 at 13:03
  • @fge Yes, it's called aggregate initialisation and is further explained in detail here Commented Dec 10, 2017 at 11:12

3 Answers 3

72

The syntax in C++ is almost exactly the same (just leave out the named parameters):

mydata data[] = { { "Archimedes", 2.12 }, 
                  { "Vitruvius", 4.49 } } ;

In C++03 this works whenever the array-type is an aggregate. In C++11 this works with any object that has an appropriate constructor.

Sign up to request clarification or add additional context in comments.

3 Comments

I thought that uniform initialization usually referred to the list-initialization form (i.e. without the =)? I couldn't find a reference for uniform initialization in the standard.
@BjörnPollex It would not be a bad thing to re-mention, I think.
This appears to be a gcc extension. As far as I can make out, it's not standard C++ and is unlikely to work in other compilers. It doesn't work in Visual Studio, anyway.
0

In my experience, we must set the array size of data and it must be at least as big as the actual initializer list :

//          ↓
mydata data[2] = { { "Archimedes", 2.12 }, 
                  { "Vitruvius", 4.49 } } ;

Comments

-3

The below program performs initialization of structure variable. It creates an array of structure pointer.

struct stud {
    int id;
    string name;
    stud(int id,string name) {
        this->id = id;
        this->name = name;
    }
    void getDetails() {
        cout << this->id<<endl;
        cout << this->name << endl;
    }
};

 int main() {
    stud *s[2];
    int id;
    string name;
    for (int i = 0; i < 2; i++) {
        cout << "enter id" << endl;
        cin >> id;
        cout << "enter name" << endl;
        cin >> name;
        s[i] = new stud(id, name);
        s[i]->getDetails();
    }
    cin.get();
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.