Hello,
I am having trouble initializing a struct array. Here is a simplified version of my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
struct Rect
{
int width;
int height;
public:
Rect(int _w, int _h)
{
width = _w;
height = _h;
}
};
int main()
{
Rect rectangles[10]; // I can initialize the array this way if the struct doesnt have a constructor, so I guess there is a problem with that.
}
I'm working in codeblocks and the error that I get is here:
error: no matching function for call to 'Rect::Rect()'|
Is it a problem with the syntax or is it something with the logic?
Thanks for the help :)
Since you defined a multiple argument constructor the default no argument constructor will not be provided by the compiler you either need to implicitly tell the compiler to create the default constructor or supply your own no argument constructor.
It works without a constructor because C++ uses a default constructor in that case.
If you define a constructor yourself, you no longer have a default constructor so it won't work.
You should either add your own default constructor (i.e. a Rect() without arguments)
Or use some of the alternatives bellow.
With dynamic memory:
1 2 3 4 5 6 7
int main()
{
Rect** rectangles = new Rect*[10];
for (int i=0; i<10; ++i) {
rectangles[i] = new Rect(500, 500);
}
}
With std::vector.
1 2 3 4
int main()
{
std::vector<Rect> rectangles(10, Rect(500, 500));
}