dfg
dfg

Reputation: 797

How to initialize array of objects?

Define an array of strings and initialize every other element to "widget". Elements not initialized to "widget" should be initialized by the default constructor.

How would I do this? The only way to initialize an array is with the default constructor. I was thinking about doing something like this, but wasn't sure if this would be valid:

string strings[3] = {string(), string ("widget"), string()};

Upvotes: 1

Views: 74

Answers (3)

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7128

When you do:

string strings[3] = {string(), string ("widget"), string()};

You are specifying the array size explicitly (could have been implicit from the contents), as content you are providing individual string objects causing the initilaization of the contents done by calling copy constructors again (unnecessary although correct), so you could do as well as:

string strings[] = {"", "widget", ""};

Upvotes: 1

R Sahu
R Sahu

Reputation: 206747

string strings[] = {{}, {"widget"}, {}, {"widget"}};

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 60047

You can do

string strings[] = {"", "widget", ""};

The compiler will figure out the rest

Upvotes: 0

Related Questions