Search code examples
c++staticoperator-overloadingfriend

Can function comparators be static function?


I have implemented two operator overloading for Point2D class

  1. operator<
  2. operator>

In header file I need to declare as friend function otherwise i get compilation errors.
Question : Are operator overloading functions always friend functions? Can it be static? I tried using as static function but there's an error:

Point2D.h:19:58: error: ‘static bool Point2D::operator<(const Point2D&, const Point2D&)’ must be either a non-static member function or a non-member function
In file included from Point2D.cpp:3:0:
Point2D.h:19:58: error: ‘static bool Point2D::operator<(const Point2D&, const Point2D&)’ must be either a non-static member function or a non-member function
Point2D.h: In function ‘bool operator<(const Point2D&, const Point2D&)’:
Point2D.h:23:7: error: ‘int Point2D::x’ is protected
Point2D.cpp:36:11: error: within this context
Point2D.h:24:7: error: ‘int Point2D::y’ is protected
Point2D.cpp:36:17: error: within this context

class Point2D
{

    friend ostream &operator<<( ostream &output, const Point2D &P);
    friend bool operator<(const Point2D& A, const Point2D& B);
    friend bool operator>(const Point2D& A, const Point2D& B);      

    protected:  
        int x;
        int y;
    public:
        //Constructor
        Point2D();
        Point2D (int x, int y);

        //Accessors
        int getX();
        int getY();

        //Mutators
        void setX (int x);
        void setY (int y);
};


ostream &operator<<( ostream &output, const Point2D &P)
              { 
             output << "X : " << P.x << "Y : " << P.y;
             return output;            
              }

    bool operator<(const Point2D& A, const Point2D& B ) 
    {
        return A.x < B.y;
    };


    bool operator>(const Point2D& A, const Point2D& B ) 
    {
        return A.x > B.y;
    };

Solution

  • Binary operators could be implemented as global binary functions, or unary member functions. In the latter, the first operand of the operator is passed implicitly (Is *this, as in all member functions):

    Option 1: Global function

    struct foo
    {
        int a;
    };
    
    bool operator==( const foo& lhs , const foo& rhs )
    {
        return lhs.a == rhs.b;
    }
    

    Option 2: Member function

    struct foo
    {
        int a;
    
        bool operator==( const foo& rhs )
        {
    //             +---- this->a
    //             |
    //             v
            return a == rhs.a;
        }
    };
    

    Option 3: Global function inside the class, declared as friend (My favorite)

    struct foo
    {
        int a;
    
        friend bool operator==( const foo& lhs , const foo& rhs )
        {
            return lhs.a == rhs.b;
        }
    };
    

    For a complete and in depth guide about operator overloading, check this C++ wiki thread: Operator overloading