Reputation: 105
I already posted another question regarding structs versus classes. I believe I got good feedback, so I went back to work on my code. Here is what confused me (maybe it is childish ;) )
I need to Have a class (or struct doesnt really mind) that is called cPoint, and it just defines a Point in space with X, Y coordinates. from it all shape-classes will derive. So for cRectangle, that is a class for rectangles, the cPoint will be used as a base element. To instantiate a Rectangle, the caller must provide the coordinates of 2 points, that will be the rectangles UpperLeft & LoowerRight corners respectively. What I want the cRectangle constructor to do, is to instantiate these two points, as it own private points and use them to define the rectangle, do calculations etc. These two points should not be visible to public scope, so a caller can't change them directly. Here is an example(wrong obviously) for what I try to do:
class cPoint
{
public:
int X,Y;
cPoint();
cPoint(int x, int y)
{
X=x;
Y=y;
}
};
class cRectangle
{
friend class cPoint;
public:
Rectangle(int x1,int y1,int x2,int y2) //the constructor of cRectangle
{
ul(x1,y1);
dr(x2,y2);
}
unsigned int area()
{
return((dr.X-ul.X) * (dr.Y-ul.Y));//example function that uses ul,dr
}
private:
cPoint ul; //uP lEFT point
cPoint dr; //dOWN Right point
};
The error that i get is " Error 1 no match for call to '(cPoint) (int&, int&)' "
Thank you
Upvotes: 0
Views: 89
Reputation: 55395
Once you enter the body of a constructor, all members are initialized and you can only assign to them and everything else that you can do to a living object.
By the point you attempt this
ul(x1,y1);
dr(x2,y2);
ul
and dr
have already been default initialized (default constructor is the one that's called if you don't explicitly initializer members - read on). When compiler sees these two lines, it looks like you're trying to call overloaded operator()
that doesn't exist, so it naturally reports an error.
To initialize members, use constructor initialization list:
Rectangle(int x1,int y1,int x2,int y2)
: ul(x1,y1), dr(x2,y2) // <-- initialization list
// using cPoint::Cpoint(int, int) constructor
{
// note, empty body
}
Upvotes: 1
Reputation: 29724
/* use initilization list */
Rectangle(int x1,int y1,int x2,int y2) : ul(x1,y1), dr(x2,y2)
{
}
Your code won't compile because here
Rectangle(int x1,int y1,int x2,int y2) //the constructor of cRectangle
{
ul(x1,y1);
dr(x2,y2);
}
you wanted to call operator(int,int)
on instances of cPoint
class and definition of this operator has been not provided.
Upvotes: 1