I have a situation similar to the following.
class Point
{
void setCoord(int x, int y)
{
this->x = x;
this->y = y;
}
private:
int x,y;
}
class Line
{
public:
Point *p1;
Point *p2;
}
The Line constructor and destructor look like
Line::Line()
{
p1 = new Point();
p2 = new Point();
}
Line::~Line()
{
delete p1;
delete p2;
}
Now, in the application can call methods of the inner object Point.
int main()
{
Line line;
line.p1->setCoord(x1,y1);
line.p2->setCoord(x2,y2);
}
I have received some suggestions that 1) "has-a" relationship is bad and that 2) the pointers to the p1 and p2 and can be replaced.
I agree with the 2nd point is valid. Can we prevent the pointers being replaced by the application?
However, I am not convinced about the 1st point. Is "has-a" relationship bad for classes containing multiple instances of the same inner class? Is there a better way to model the classes in this case?
EDIT:
A few clarifications to the problem based on the comments on this question and the answers. The members x and y of Point cannot be made public but can only be manipulated through the public function setCoord.
Even if I replace Point *p1, *p2 with Point p1, p2, someone can just do line.p1 = Point() and change p1 and p2. Need to prevent this as well.