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

How Can I Initialize an Object Array in C Without a Public Default Constructor?

DDD
Release: 2024-12-26 01:57:09
Original
260 people have browsed it

How Can I Initialize an Object Array in C   Without a Public Default Constructor?

Object Array Initialization without Default Constructor

In C , when attempting to initialize an array of objects without a publicly accessible default constructor, one encounters an error as exemplified in the code snippet below:

class Car
{
private:
  Car(){}; // Default constructor hidden
};

int main()
{
  Car *cars = new Car[10]; // Error: Default constructor not accessible
}
Copy after login

This error occurs because the private default constructor for Car cannot be invoked directly. However, there is a solution that allows for the creation of such an array without making the default constructor public.

Solution: Placement-New

Placement-new is a technique that allows for the creation of objects directly at a specified memory location. It can be used to bypass the default constructor's accessibility restrictions. The code below demonstrates its usage:

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

int main()
{
  void *raw_memory = operator new[](NUM_CARS * sizeof(Car)); // Allocate raw memory
  Car *cars = static_cast<Car *>(raw_memory);
  // Initialize objects at specific memory locations
  for (int i = 0; i < NUM_CARS; ++i) {
    new(&amp;cars[i]) Car(i);
  }
}
Copy after login

By utilizing placement-new, objects can be created at the allocated memory location without the need for a public default constructor.

Conclusion

By using placement-new, it becomes possible to initialize arrays of objects even when the default constructor is private. This technique provides greater flexibility and allows for the creation of complex object arrays without compromising encapsulation principles.

The above is the detailed content of How Can I Initialize an Object Array in C Without a Public 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template