Home > Article > Backend Development > How to Properly Initialize Arrays of Objects in C ?
How to Initialize Arrays of Objects in C
In C , initializing an array of objects may seem straightforward, but there are some intricacies to consider. Consider the following struct and class definitions:
struct Foo { Foo(int x) { /* ... */ } }; struct Bar { Foo foo; Bar() : foo(4) {} // Valid initialization }; struct Baz { Foo foo[3]; // Incorrect initialization Baz() : foo[0](4), foo[1](5), foo[2](6) {} };
The initialization of Bar using foo(4) is valid since it invokes the constructor of Foo to initialize the foo member. However, the attempt to initialize Baz in the provided way is incorrect.
Correct Array Initialization
Unlike Bar, where there is a single object of type Foo, Baz contains three objects of the same type. To properly initialize the array of objects in Baz, the following approach must be taken:
Baz() { foo[0] = Foo(4); foo[1] = Foo(5); foo[2] = Foo(6); }
This explicitly calls the constructor for each object in the array.
Workaround for Embedded Processors
In the absence of standard library constructs like std::vector, an alternative approach is to utilize a default constructor along with an explicit initialization method, such as init(), allowing you to defer initialization until after construction:
Baz() {} void Baz::init() { foo[0] = Foo(4); foo[1] = Foo(5); foo[2] = Foo(6); }
The above is the detailed content of How to Properly Initialize Arrays of Objects in C ?. For more information, please follow other related articles on the PHP Chinese website!