Home > Backend Development > C++ > How to Initialize Object Arrays Without a Default Constructor?

How to Initialize Object Arrays Without a Default Constructor?

Mary-Kate Olsen
Release: 2024-12-27 06:15:12
Original
780 people have browsed it

How to Initialize Object Arrays Without a Default Constructor?

Initializing Object Arrays Without Default Constructor

Object arrays are commonly used in programming, but issues may arise when initializing them with classes lacking default constructors. Consider the following code:

class Car {
private:
  Car(){};  // Private default constructor
  int _no;
public:
  Car(int no) {
    _no = no;
  }
};
Copy after login

Within this class, the default constructor (Car()) is private, which means objects of type Car cannot be created without providing arguments. However, when initializing an array of Car objects, the compiler attempts to call the default constructor for each element, leading to the error:

cartest.cpp:5: error: ‘Car::Car()’ is private
cartest.cpp:21: error: within this context
Copy after login

Solution Using Placement-New

To overcome this issue, placement-new can be employed. Placement-new allows us to allocate memory and construct objects directly in that memory location without invoking the object's constructor. Here's how it can be implemented:

int main() {
  void *raw_memory = operator new[](NUM_CARS * sizeof(Car));  // Allocate raw memory
  Car *ptr = static_cast<Car *>(raw_memory);  // Cast to a pointer to Car
  for (int i = 0; i < NUM_CARS; ++i) {
    new(&amp;ptr[i]) Car(i);  // Call placement-new to construct Car objects in-place
  }
}
Copy after login

By using placement-new, we can initialize the object array without explicitly calling the default constructor. The objects are created and placed directly into the allocated memory.

Advantages of Avoiding Default Constructors

As mentioned in Item 4 of Scott Meyers' "More Effective C ", avoiding gratuitous default constructors can enhance program correctness and maintainability. Default constructors often lead to ambiguity in class design and can make it challenging to enforce class invariants. By explicitly defining constructors, the programmer asserts that objects of that class can only be created with specific sets of arguments, ensuring greater control and clarity.

The above is the detailed content of How to Initialize Object Arrays 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