Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare an array of objects whose class has no default constructor?

Tags:

c++

arrays

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 Foo{

public:
Foo(int i) {}

}

How to declare an array or a vector which contains 10000 Foo objects?

like image 255
skydoor Avatar asked Feb 26 '10 17:02

skydoor


People also ask

Can a class have no default constructor?

No default constructor is created for a class that has any constant or reference type members. A constructor of a class A is trivial if all the following are true: It is implicitly defined. A has no virtual functions and no virtual base classes.

Can we create an array of objects for a class having user defined constructor?

One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.

Can we declare array without initialization?

Declaring an array does not initialize it. In order to store values in the array, we must initialize it first, the syntax of which is as follows: datatype [ ] arrayName = new datatype [size]; There are a few different ways to initialize an array.

Can we create an array of objects for a class having default constructor justify your answer?

yes but you're allocating as char, then reinterpreting the pointer. It won't necessarily be properly aligned for the reinterpreted type.


1 Answers

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.

like image 141
fogo Avatar answered Oct 29 '22 06:10

fogo