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

How to Properly Initialize Arrays of Objects in C ?

Linda Hamilton
Release: 2024-11-07 01:53:02
Original
394 people have browsed it

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) {}
};
Copy after login

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);
}
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template