Why this operator overload does not work?

  • 1
    friend bool operator==(Point &p1, Point &p2) {
        return p1.x==p2.x && p1.y==p2.y;

    when I define this function in side the class, it does not work. But when I define it outside the class, it works.
    It also did not work on my local compiler.
    Anybody good at C++ knows why?


  • 0

    Friend functions can be called without any reference by the class object and are non-static , hence are non-member functions and should be globally defined.

    They have access to the private data members of the class being referred , hence the declaration of the friend function must be present inside the class.

    PS: The reason we have to pass the calling object in the friend function is because 'this' pointer is not available inside a friend function.'this' pointer is passed only to the nonstatic member functions of a class.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.