Rectangle inside another Rectanle Class Question

I'm wondering if my formula for computing the function looks right..? Below is my code:

1
2
3
4
5
6
7
  Rectangle2D r1(2, 2, 5.5, 4.9);     // Instantiate r1 object
  Rectangle2D r2(4, 5, 10.5, 3.2);   // Instantiate r2 object
// Check if r2 is inside r1
	  if (r1.contains(r2))
		  cout << "Rectangle r2 is inside rectangle r1 " << endl;
	  else
		  cout << "Rectangle r2 is not inside rectangle r1 " << endl;

Constructor format is:
1
2
3
4
5
6
7
8
9
// Overloaded constructor
// x and y represent the center of the rectangle
Rectangle2D::Rectangle2D(double x, double y, double height, double width)
{
   setx(x);
   sety(y);
   setHeight(height);
   setWidth(width);
}          

Contains function is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool Rectangle2D::contains(Rectangle2D &Rec)
{
	double x = Rec.getx();
	double y = Rec.gety();
	double width = Rec.getWidth();
	double height = Rec.getHeight();

	/*
	Below is comparing the sides of the inner rectangle to the sides of the outer rectangle
	if Right2 < Right1 && Left2 > Left1 && Top2 < Top1 && Bottom2 > Bottom1
	*/
	if ((x + (.5*width)) < (this->x + (.5*this->width)) && (x - (.5*width)) > (this->x - (.5*this->width)) &&
(y + (.5*height)) < (this->y + (.5*this->height)) && (y - (.5*height)) > (this->y - (.5*this->height)))
		return true; // One is inside the other
	else
		return false;
}


IMO the formulas are correct, but just as a remark, I would avoid double where I can.

For example x + 0.5 * w < X + 0.5 * W is equivalent to 2 * (x - X) < W - w. Now, if the original coordinates are integers, you can avoid floating-point entirely.

Side note: In case you decide to use the integer approach (which you have no real reason to do) and feel tempted to convert (2 * (x - X)) to ((x - X) << 1), don't. The compiler will do it for you and it will only spoil the readability.

Regards
Last edited on
I get what you mean. Thanks!
Topic archived. No new replies allowed.