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?
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.
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.
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.
yes but you're allocating as char, then reinterpreting the pointer. It won't necessarily be properly aligned for the reinterpreted type.
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.
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