3

I want to have an array of objects. Each object has a constructor with one argument. My object array initialisation :

set s[]=new set[n]; // creates an array of n objects of class set

However, it says that I cannot do so, because my constructor requires an argument. My Constructor:

set(int size){}

I've understood the problem, but cant think of a good solution. What I can do, is either initialise each object seperately :

set s1(size);
set s2(size); //& so on.....

or remove the argument from constructor......both solutions are not quite satisfactory

Can anyone help me out to find a better solution to this ?

Note: 'size' value of each object is different/dynamic

2 Answers 2

4
#include <vector>
...
std::vector<set> s(n, set(x,y,z));

This will create a vector (a dynamically resizeable array) of n set objects, each a copy of set(x,y,z). If you want to use different constructors for various elements, or the same constructor with different arguments:

std::vector<set> s;      // create empty vector
s.push_back(set(x,y,z));
s.push_back(set(y,z,x));
...
... // repeat until s.size() == n
Sign up to request clarification or add additional context in comments.

Comments

0

You can make a different constructor that takes no arguments and initializes the values, and then set the values of each variable in a loop

set() {
    this.size = 0;
}

and then in a for loop initialize each element with the desired size, using direct binding or a getter/setter functions.

for(int i = 0; i < n; i++) {
    s[i].size = value[i]; // or create a setter function
}

1 Comment

Yeah, I had the same thing in mind earlier, but I specifically wanted to initialise it using constructor. Thanks for the effort.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.