For example, I have the following C++ class:
struct A {
A(const int value) {}
};
If I want a single object, I can do this:
A a = A(3);
I would like to construct 10 of these objects, I don't know how to instantiate statically.
A a[10]; // This won't compile, as struct A constructor needs an argument
I can use a pointer A *a
, and then create the object one by one, but I am not sure if there is new feature in C++11
available which allows I can do these in 1 shot statically?
Array of Objects in c++ Like array of other user-defined data types, an array of type class can also be created. The array of type class contains the objects of the class as its individual elements. Thus, an array of a class type is also known as an array of objects.
An array of objects, all of whose elements are of the same class, can be declared just as an array of any built-in type. Each element of the array is an object of that class. Being able to declare arrays of objects in this way underscores the fact that a class is similar to a type.
The syntax for creating n objects is: object o[n]; All objects in o will be fully allocated and have their constructors called. They are ready to take data and perform their member functions.
List initialization allows you to write
A a[10]{0,1,2,3,4,5,6,7,8,9};
Each element in the list will be passed to A
's constructor.
Live demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With