Home > Backend Development > C++ > How to Initialize an Object Array in C Without a Default Constructor?

How to Initialize an Object Array in C Without a Default Constructor?

Susan Sarandon
Release: 2024-12-22 11:02:10
Original
796 people have browsed it

How to Initialize an Object Array in C   Without a Default Constructor?

Object Array Initialization Without Default Constructor

In C , when creating an array of objects, the default constructor is called to initialize each element. However, in some cases, you may encounter an error when initializing an array of objects if the default constructor is private or doesn't exist.

To overcome this, you can employ the technique of placement-new, which provides a way to initialize objects in situ, without invoking the default constructor.

Here's how you can use placement-new to initialize an array of objects without a default constructor:

class Car {
private:
    int _no;
public:
    Car(int no) : _no(no) {}
};

int main() {
    void *raw_memory = operator new[](NUM_CARS * sizeof(Car));
    Car *ptr = static_cast<Car *>(raw_memory);
    for (int i = 0; i < NUM_CARS; ++i) {
        new(&amp;ptr[i]) Car(i);
    }

    // destruct in inverse order
    for (int i = NUM_CARS - 1; i >= 0; --i) {
        ptr[i].~Car();
    }
    operator delete[](raw_memory);

    return 0;
}
Copy after login

In this code, raw_memory represents the raw memory block used to store the array of Car objects. We then cast it to a Car * pointer and use placement-new to construct each object in place, initializing it with the specified number.

When you're done with the array, remember to destruct the objects in reverse order and delete the raw memory allocated using placement-new. This approach allows you to initialize an array of objects even if their default constructor is inaccessible.

The above is the detailed content of How to Initialize an Object Array in C Without a Default Constructor?. 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