I wonder how to initialize each object in a dynamically allocated array with some arguments.
I'm aware of that how to initialize all objects in a dynamically allocated array with a default constructor.
For example, Suppose there is a class named Circle, which has a member variable named radius. I know
Circle *arr=new Circle[5]
means a Circle object is constructed by the default constructor.
But how can I do some work like this? (though this doesn't work.)
Circle *arr=new Circle[5](10)
Following is the whole code that you can refer to.
#include <iostream>
using namespace std;
class Circle
{
private:
int radius;
public:
Circle(int r)
{
cout << "radius : " << r << endl;
this->radius = r;
}
Circle()
{
cout << "radius : 0" << endl;
this->radius = 0;
}
~Circle()
{
cout << "deleted" << endl;
}
};
int main()
{
Circle *arr = new Circle[5];
// Here, What I want is something like this
// Circle *arr = new Circle[5](10) //10 would be an argument meaning radius
delete[] arr;
system("pause");
}
std::vector.std::vector<Circle> arr(5, 10)will do the job, without the need for explicitly using dynamic memory allocation.