Firstly I want to clarify that there is a bug in your code in printCarNumbers
function, you are trying to send void to the standard output using std::cout
as shown below :
void printCarNumbers(Car *cars, int length)
{
for(int i = 0; i < length; i++)
std::cout << cars[i].printNo();
}
since printNo()
is used for printing then just call it directly:
for(int i = 0; i < length; i++)
cars[i].printNo();
let's return to the subject, you are trying to allocate an array of objects using new
like this :
Car *mycars = new Car[userInput];
but with this syntax, you actually trying to allocate an array of objects that has userInput
size (well that's what we want), but the problem is that it tries to call the default constructor for each object, and the default constructor is declared as private, so it can't find it, that's why you got that error :
cartest.cpp:5: error: ‘Car::Car()’ is private
instead of that you need to do it in this way :
Car *mycars = (Car*) ::operator new (sizeof(Car));
// allocates memory by calling: operator new (sizeof(Car))
// but does not call Car's constructor
as described in the comments, calling new
in this way, allocates memory for you without calling the default constructor, for more details check new operator
and now if you want to call the parametrized constructors, you need to call it for each object separately as the following :
for(int i =0; i < userInput; i++)
new (&mycars[i]) Car(i + 1); // does not allocate memory -- calls: operator new (sizeof(Car), &mycars[i])
// but constructs an object at mycars[i]
you might be confused now, since we called new
again, but this syntax for new is not allocating any memory, it's just calling the constructor of the indexed object.
and here is the full functioning code for anyone wants to test :
#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++)
cars[i].printNo();
}
int main()
{
int userInput = 10;
Car *mycars = (Car*) ::operator new (sizeof(Car));
for(int i =0;i < userInput;i++)
new (&mycars[i]) Car(i+1);
printCarNumbers(mycars,userInput);
return 0;
}
I know that I am so late, but maybe someone will find this useful, If there is any wrong statement, please be free to correct me.