If a class has only one constructor with one parameter, how to declare an array? I know that vector is recommended in this case. For example, if I have a class
class single
{
int data;
public:
single()
{
data = 0;
}
single(int i)
{
data = i;
}
};
// in main()
single* obj[10000];
for (unsigned int z = 0; z < 10000; z++)
{
obj[z] = new single(10);
}
Another option might be to use an array of boost::optional<Foo>
:
boost::optional<Foo> foos[10]; // No construction takes place
// (similar to vector::reserve)
foos[i] = Foo(3); // Actual construction
One caveat is that you'll have to access the elements with pointer syntax:
bar(*foos[2]); // "bar" is a function taking a "Foo"
std::cout << foos[3]->baz(); // "baz" is a member of "Foo"
You must also be careful not to access an unitialized element.
Another caveat is that this not a true replacement for an array of Foo
, as you won't be able to pass it to a function that expects the latter.
For an array you would have to provide an initializer for each element of the array at the point where you define the array.
For a vector you can provide an instance to copy for each member of the vector.
e.g.
std::vector<Foo> thousand_foos(1000, Foo(42));
The only way to define an array of a class with no default constructor would be to initialize it right away - not really an option with 10000 objects.
You can, however, allocate enough raw memory whichever way you want and use placement new
to create the objects in that memory. But if you want to do this, it's better to use std::vector
which does exactly that:
#include <iostream>
#include <vector>
struct foo {
foo(int) {}
};
int main()
{
std::vector<foo> v;
v.resize(10000,foo(42));
std::cout << v.size() '\n';
return 0;
}
Actually, you can do it as long you use an initialization list, like
Foo foos[4] = { Foo(0),Foo(1),Foo(2),Foo(3) };
however with 10000 objects this is absolutely impractical. I'm not even sure if you were crazy enough to try if the compiler would accept an initialization list this big.
You'd need to do an array of pointers to Foo.
Foo* myArray[10000];
for (int i = 0; i < 10000; ++i)
myArray[i] = new Foo(i);