Difficulty in implementing function based on classes

Viewed 73

I am trying to write a function that checks if a given point is included in a circle (located in the integers xy plane). For that task, I want to use classes, which I wrote as shown below.

class Point
{
public:
Point(int x, int y);
int getX() const;
int getY() const;
void setX(int x);
void setY(int y);

private:
int x, y;
};
class Circle
{
public:
Circle(int x, int y, int r);
bool contains(const Point &p) const;

private:
const Point center;
int radius;
};

I find some difficulty in writing the function 'contains'. Here is what I have done. When I wrote this function, I got an error that says that "member Point::x is inaccessible", and I cannot understand what is wrong.

bool Circle::contains(const Point &p) const
{

   if ((p.x-center.x)>=(-1*radius) && (p.x-center.x)<=radius && (p.y-center.y)>=(-1*radius) && (p.y-center.y)<=radius )
       return true;
   return false;

}

3 Answers

x is a private data member of class Point which basically means that it cannot be directly accessed from outside the Point class.

To access x from outside Point class, you need a public function that returns x.

int getX() const {
   return x;
}

Call this function whenever you need to access x from outside Point class.

You can't access private members outside of the class. In the class Point, x is a private member and therefore you can't access it from Circle.

Your code contain a public function int getX() const which was meant for your case exactly, accessing x from another context.

You should use this public member function from Circle, with it your code should look as follows:

bool Circle::contains(const Point &p) const
{
   // Copy of question code, note that this code doesn't do what you think it does
   if ((p.getX()-center.getX())>=(-1*radius) && 
       (p.getX()-center.getX())<=radius      && 
       (p.getY()-center.getY())>=(-1*radius) && 
       (p.getY()-center.getY())<=radius)
   {
       return true;
   }
   return false;
}

I guess the following code is ok. I am not wrong , am I?

bool Circle::contains(const Point &p) const
{
    int distX, distY;

    distX=p.getX()-center.getX();
    distY=p.getY()-center.getY();

    if ((distX*distX + distY*distY) > (radius*radius))
        return false;
    return true;
}

and thanks to all of you!

Related