Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object array initialization without default constructor

#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; }     

I want to create a car array but I get the following error:

cartest.cpp: In function ‘int main()’: cartest.cpp:5: error: ‘Car::Car()’ is private cartest.cpp:21: error: within this context 

is there a way to make this initialization without making Car() constructor public?

like image 835
Dan Paradox Avatar asked Jan 21 '11 02:01

Dan Paradox


People also ask

Can array objects be initialized?

One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.

Can we create an array of objects for a class having default constructor?

You should define it in class CheckBook constructor. Show activity on this post. The correct way to build an array of objects having no default constructor is to use the placement new syntax to separate the allocation of the array and the construction of the objects.

Can a class have no default constructor?

No default constructor is created for a class that has any constant or reference type members.

Can an array be initialized in a constructor?

Initialize Array in Constructor in JavaWe can create an array in constructor as well to avoid the two-step process of declaration and initialization. It will do the task in a single statement. See, in this example, we created an array inside the constructor and accessed it simultaneously to display the array elements.


1 Answers

You can use placement-new like this:

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(&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; } 

Reference from More Effective C++ - Scott Meyers:
Item 4 - Avoid gratuitous default constructors

like image 153
Chan Avatar answered Sep 24 '22 00:09

Chan