Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ an array of objects instantiation (I'm trying to find a compile time solution)

Tags:

c++

c++11

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?

like image 306
Carson Pun Avatar asked Jul 28 '16 21:07

Carson Pun


People also ask

What is an array of objects in C++?

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.

What is an array object?

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.

How do you create an n number object in C++?

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.


1 Answers

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

like image 116
Praetorian Avatar answered Sep 30 '22 01:09

Praetorian