Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment of a complex constructor through new

I have a confusion. Following is a code snippet.

I want to create a dynamic array of five class objects using newand 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?

like image 353
tariq zafar Avatar asked Dec 21 '22 08:12

tariq zafar


1 Answers

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));
}
like image 58
juanchopanza Avatar answered Dec 24 '22 02:12

juanchopanza