185. Friend Function

Question.2

A developer needs int + Vec to work (not just Vec + int):

class Vec {
   int x;
public:
   Vec(int v) : x(v) {}
   friend Vec operator+(int n, const Vec& v) {
       return Vec(n + v.x);
   }
};

Vec a(10);
Vec b = 5 + a;  // int on the LEFT

Why must operator+ be a friend instead of a member?

Need Help? Refer to the Quick Guide below

Select Answer