I have a confusion. Following is a code snippet.
I want to create a dynamic array of five class objects using new
and but i want to run a loop to assign the first parameter of constructor using the loop counter. Something like.
class A {
public:
A(int _x, int _y):x(_x),y(_y) {}
private:
int x,y;
};
int main() {
A* a = new A[5]; //compiler error
for(i=0;i<5;i++) {
a[i] = A(i, 10);
}
}
Can some one please tell me whats the correct syntax to do this as I dont have a simple constructor?
This line
A* a = new A[5];
requires that A
be default constructible. So an easy option would be to add a default constructor to A
:
A(): x(), y() {} // zero-initializes x and y
Note that in C++ one would usually favour using an std::vector<A>
in this case. It takes case of all memory management, so it is not necessary to call new
and delete
explicitly. It can also be resized dynamically. This would construct an std::vector<A>
with five default constructed A
objects:
std::vector<A> a(5);
although you probably want to create an empty one and push values into it in a loop.
std::vector<A> a;
for(i=0;i<5;i++) {
a.push_back(A(i, 10));
}
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