Reputation: 1091
I have always been using vectors for storing objects when a list type container is required. I wanted to know how you can pass constructors to array pointers.The following works in C++03 if the object foo did not have a constructor
foo* p = new foo[5]()
Now what if the constructor of foo
required an int
how would I pass the constructor in the above statement?
Upvotes: 1
Views: 126
Reputation: 477100
Since C++11, you can use brace initializers:
foo * p = new foo[5] { 1, 2, 3, 4, 5 }; // better: "auto p = ..."
This assumes that foo
is implicitly constructible from int
.
But you can just as well use containers:
std::vector<foo> v { 1, 2, 3 };
std::list<foo> w { 1, 2, 3 };
Or perhaps:
std::unique_ptr<foo[]> q(new foo[4] { 1, 2, 3, 4} );
Upvotes: 3
Reputation: 18228
It is not possible. Your foo
instances can only be default-constructed.
UPDATE 1
If your foo
does not have a default constructor then you will get a compiler error either about use of deleted function or about no matching ctor.
UPDATE 2
I see that others offer C++11 solution. My answer appears to be correct only for C++03 or earlier.
Upvotes: 3
Reputation: 63775
how would I pass the constructor in the above statement?
new[]
does not have a form for forwarding constructor parameters.
You would instead call the constructors yourself.
foo* p = new foo[5]{ foo(1), foo(2), foo(3), foo(4), foo(5) };
Upvotes: 1