Search code examples
c++operator-overloadingfriendconst-reference

using friend function with const reference in operator overloading


The code below cannot be compiled. However, when I remove "const" from Point& of the friend function, this code turns to be compiled. Could anyone explain the reason why?

class Point
{
  public:
    Point(double x, double y);
    Point operator+(const double& add);
    friend Point operator+(const double& add, const Point& p){return p+add;}
  private:
    double px, py;
};

Point::Point(double x, double y): px(x), py(y){}
Point Point::operator+(const double& add){
  return(Point(px+add, py+add));
}
int main(){}

Solution

  • The operator+ is not marked as a const, yet is tried to be called through a const reference. Constant pointers and references are only allowed to call member functions that are marked constant (since the compiler definitely knows that those functions are ensured not to modify internal state).