Home >Backend Development >C++ >How to Initialize Arrays of Objects with Constructors in C ?

How to Initialize Arrays of Objects with Constructors in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 05:23:02802browse

How to Initialize Arrays of Objects with Constructors in C  ?

C : Constructor Initializers for Arrays

In C , initializing an array of objects can be a challenge. For non-array scenarios, one can utilize constructor syntax like so:

struct Foo {
    Foo(int x) { /* ... */ }
};

struct Bar {
    Foo foo;

    Bar() : foo(4) {}
};

However, the issue arises when dealing with arrays:

struct Foo {
    Foo(int x) { /* ... */ }
};

struct Baz {
    Foo foo[3];

    // Incorrect syntax
    Baz() : foo[0](4), foo[1](5), foo[2](6) {}
};

Unfortunately, in C (prior to more recent iterations of the language), there is no straightforward method to initialize array members using constructors. The limitation stems from the requirement of default constructors for array members, which are automatically invoked during array initialization. Afterward, any additional initialization within the constructor proceeds. For embedded systems lacking STL functionality, one workaround involves a default constructor alongside an explicit init() method callable post-construction, obviating the need for initializers.

The above is the detailed content of How to Initialize Arrays of Objects with Constructors in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn