error: no matching function for call

This code from http://www.cplusplus.com/doc/tutorial/classes/ as it is gives compile error I can't understand.

#include <iostream>
using namespace std;

class Rectangle {
int width, height;
public:
Rectangle(int x, int y) : width(x), height(y) {}
int area(void) { return width * height; }
};

int main() {
Rectangle * baz;
baz = new Rectangle { {2,5}, {3,6} };
delete[] baz;
return 0;
}

Gives error (g++ first.cpp)
first.cpp: In function ‘int main()’:
first.cpp:14:38: error: no matching function for call to ‘Rectangle::Rectangle(<brace-enclosed initialiser list>)’
Please use code tags.

Anyways, defining a constructor disallows C-style initialization. Call the constructor for Rectangle instead.
The compiler is probably trying to use uniform initialization. Your constructor only takes two integers, but you are passing two pairs of two integers, so it doesn't match the signature of the constructor you declared.

Also, why are you using array delete without array new? I assume that you were trying to make an array of rectangle by passing those two pairs of ints, but that is not how it works.

Try this for one rectangle:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Rectangle
{
    int width, height;

    public:
        Rectangle(int x, int y) : width(x), height(y) {}
        int area(void) { return width * height; }
};

int main()
{
    Rectangle * baz;
    baz = new Rectangle {2,5};
    delete baz;

    return 0;
}


Or try this for multiple rectangles:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Rectangle
{
    int width, height;

    public:
        Rectangle() = default;
        Rectangle(int w, int h) : width(w), height(h) {}

        void setWidth(int w) { width = w; }
        void setHeight(int h) { height = h; }

        int area() { return width * height; }
};

int main()
{
    Rectangle* baz;
    baz = new Rectangle[2];

    baz[0].setWidth(2); baz[0].setHeight(5);
    baz[1].setWidth(3); baz[0].setHeight(6);
    //etc...

    delete[] baz;
    return 0;
}
Thanks for replies.

Are you guys saying following code is wrong as given in tutorial. Please see complete code in the link.

baz = new Rectangle { {2,5}, {3,6} };

This code should allocate 2 rectangle objects and initialize with given values.

Exactly same way as below which works.

Rectangle rects[2] = { {2,5}, {3,6} };

Topic archived. No new replies allowed.