Home > Backend Development > C++ > Can Object Array Initialization Be Achieved Without a Public Default Constructor?

Can Object Array Initialization Be Achieved Without a Public Default Constructor?

Patricia Arquette
Release: 2024-12-20 09:41:10
Original
199 people have browsed it

Can Object Array Initialization Be Achieved Without a Public Default Constructor?

Object Array Initialization without Default Constructor

Consider the following code:

#include <iostream>
class Car
{
private:
  Car(){};
  int _no;
public:
  Car(int no)
  {
    _no=no;
  }
  void printNo()
  {
    std::cout<<_no<<std::endl;
  }
};
void printCarNumbers(Car *cars, int length)
{
    for(int i = 0; i<length;i++)
         std::cout<<cars[i].printNo();
}

int main()
{
  int userInput = 10;
  Car *mycars = new Car[userInput];
  for(int i =0;i < userInput;i++)
         mycars[i]=new Car[i+1];
  printCarNumbers(mycars,userInput);
  return 0;
}
Copy after login

This code aims to create an array of cars, but when compiled, it encounters an error stating that the Car() constructor is private. The question is, can the initialization be performed without making the Car() constructor public?

Solution

To address this issue, placement-new can be utilized as follows:

class Car
{
    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

Placement-new allows memory to be allocated and an object to be constructed at a specific location. In this case, raw_memory is allocated, and then placement-new is used to construct Car objects at the addresses pointed to by ptr.

By leveraging placement-new, the initialization of the array of cars can be achieved while respecting the privacy of the Car() constructor

The above is the detailed content of Can Object Array Initialization Be Achieved 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template