Alex Rivera | Logout

Initializing structs in C++

Asked 2010-05-14T22:45:49.493
28

As an addendum to this question, what is going on here:

#include <string>
using namespace std;

struct A {
    string s;
};

int main() {
    A a = {0};
}

Obviously, you can't set a std::string to zero. Can someone provide an explanation (backed with references to the C++ Standard, please) about what is actually supposed to happen here? And then explain for example):

int main() {
    A a = {42};
}

Are either of these well-defined?

Once again an embarrassing question for me - I always give my structs constructors, so the issue has never arisen before.

Edit
Report

1 Answer

8

8.5.1/12 "Aggregates" says:

All implicit type conversions (clause 4) are considered when initializing the aggregate member with an initializer from an initializer-list.

So

A a = {0};

will get initialized with a NULL char* (as AndreyT and Johannes indicated), and

A a = {42};

will fail at compile time since there's no implicit conversion that'll match up with a std::string constructor.

answered 2010-05-14T22:53:27.587

Your Answer