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 }
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.
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(&cars[i]) Car(i); } }
By utilizing placement-new, objects can be created at the allocated memory location without the need for a public default constructor.
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!