1

I have class Line, which represent 2 dimensional line. It has function for checking if 2d point lie on this line.

class Line
{
    private:
       float a,b,c: //line coefficients
    public:
    bool checkPointOnLine();
    .....
}

now I have to check find point of intersectionof 2 lines. I'm wondering if it is better to put new member function in class Line like

class Line
{
    private:
       float a,b,c: //line coefficients
    public:
    bool checkPointOnLine();
    Point getIntersectionPoint(const  Line& line);
    .....
}

or to use non member function

Point getIntersectionPoint(const Line& l1,const Line& l2);
Vladimir Yanakiev
  • 860
  • 10
  • 21
  • see here: http://stackoverflow.com/questions/5989734/effective-c-item-23-prefer-non-member-non-friend-functions-to-member-functions – Hayt Sep 29 '16 at 12:54

1 Answers1

2

Although to a large measure this is a matter of preference, a static or non-member function approach is slightly more preferable because of symmetry.

When two calls

a.someFunction(b)

and

b.someFunction(a)

always return the same result, a symmetric function

someFunction(a, b)

is more intuitive.

Note that since an intersection may not exist (for parallel lines) or have an infinite number of points (for two identical lines) returning a Point is not ideal. You would be better off returning a pair of Point and some indicator of its validity, for example

enum LineIntersectionKind {
    Valid
,   Empty
,   Infinite
};

pair<Point,LineIntersectionKind> getIntersectionPoint(const Line& l1,const Line& l2);
Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
  • I agree with your answer but in such a case I have to private members in this function (line coefficients) I have to use friend for example or to put getters for them. Or maybe the best is to put static function for this. – Vladimir Yanakiev Sep 29 '16 at 13:11
  • @VladimirYanakiev An approach that does not require friendship is to make the function static in the `Line` class, i.e. `static Line::getIntersectionPoint`. – Sergey Kalinichenko Sep 29 '16 at 13:15