i would like to use a class Point in an other class Rect.
class Point
{
int x, y;
public:
Point (int px, int py){
x = px;
y = py;
}
};
class Rect
{
Point top_left;
Point bottom_right;
public:
Rect (Point p1, Point p2){
top_left = p1;
bottom_right = p2;
}
};
error message is: "main.cpp:31:30: error: no matching function for call to ‘Rect::Point::Point()’". In my understanding the constructor method of the Rect class uses two parameters of type Point to instantiate a Rect object. I guess that i cannot use "Point" as type since it sounds to me as the compiler wants to call a function. The error message doesn’t help me so i hope you will. Thanks for that in advance.
>Solution :
Members are initialized before the body of the constructor runs. When you write:
Rect (Point p1, Point p2){
top_left = p1;
bottom_right = p2;
}
Then before the constructor is executed the members top_left and bottom_right are initialized. Because Point has no default constructor the members cannot be initialized.
To initialize members with a constructor you should use the member initializer list:
Rect (Point p1, Point p2) : top_left(p1), bottom_right(p2) { }
The error can be prevented also by providing default initializers for the members:
class Rect
{
Point top_left{0,0};
Point bottom_right{0,0};
public:
Rect (Point p1, Point p2){
top_left = p1;
bottom_right = p2;
}
};
Or by providing a default constructor for Point. A default constructor is one that can be called without parameters. However, in any case you should prefer the member initializer list over assignment in the constructor body, because initialization + assignment is more expensive than initialization only.