Dirk
Dirk

Reputation: 1849

Array initialization with only one constructor call

In cpp, is this or something equivalent possible?

Foo bar[23] = Foo();

EDIT:

The motivation for the question was that I think I saw somebody using this syntax

vtkSmartPointer<Foo> bar[23] = vtkSmartPointer<Foo>::New();

and wondered why it compiles and how many new objects are actually created...

Upvotes: 0

Views: 174

Answers (4)

James Kanze
James Kanze

Reputation: 153909

Not with this syntax, but if Foo has a non-trivial default constructor,

Foo bar[23];

will call it for each member of the array. More generally, you can also write:

Foo bar[23] = { x, y, z... };

The compiler will try to convert each initializer (which can be an arbitrary expression) into a Foo, and use that to initialize the element of the array. If there are not enough initializer expressions, then all of the following elements will be initialized with Foo().

EDIT:

Since several comments asked for it: if Foo doesn't have a user defined constructor, the situation changes (since calling the "constructor" won't do anything). In that case, the behavior of:

Foo bar[23];

depends on the variables lifetime: if it has static lifetime, it will be zero initialized; otherwise, it won't be initialized at all. In either case, you can use aggregate initialization to force the initialization you want:

Foo bar[23] = { { firstMember, secondMember... }, ... };

If there aren't enough initializers, the remaining elements are zero initialized, so:

Foo bar[23] = {};

will zero initialize all of the members.

For completeness, I should point out that aggregate initialization cannot be used for class members: the only ways you can initialize a C style array member is by means of assignment to each element, in the body of the constructor, or by copy initialization: define a static Foo and initialize the member with it.

I should probably also point out that all of the above refers to C++03. C++11 introduced an extended initialization syntax; in particular, you can use something that looks like aggregate initialization for class members as well. (I think—I'm not too familiar with C++11, as not all of my compilers support it yet.)

Upvotes: 7

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76788

If you are willing to use an std::vector, you can use this:

std::vector<Foo> bar(23, Foo()); // initialize bar with 23 copies of Foo()

Upvotes: 3

Karl Knechtel
Karl Knechtel

Reputation: 61508

Try

Foo bar[23] = { Foo(), Foo(), Foo(), /* ... 23 of them */ };

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258568

You can initialize an array using the following syntax:

struct Foo
{
};

Foo x[2] = {Foo(), Foo()};
//or
Foo y[] = {Foo(), Foo()};

In the latter case, the size of the array is deduced from the initialization.

Upvotes: 1

Related Questions