#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?
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.
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.
No default constructor is created for a class that has any constant or reference type members.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With