Skip to main content

Overloading via member and non-member function

Short answer

Member functions: left operand is this; binary takes one argument, unary none. Non-member (friend): no this pointer; binary takes two arguments, unary one. Use member when left operand is class type; use friend for mixed types (e.g., cout << obj) or built-in left operand. =, [], (), -> must be members.

How can you overload operators using member function and non-member function?

An operator can be overloaded either as a member function of the class or as a non-member (usually friend) function.

Using a member function

The left operand is the calling object (this). A binary operator takes one argument; a unary operator takes none.

class Point {
    int x, y;
public:
    Point(int a = 0, int b = 0) { x = a; y = b; }
    Point operator+(Point p) {              // a + b  ->  a.operator+(b)
        return Point(x + p.x, y + p.y);
    }
};

Using a non-member function

It is declared outside the class and normally made a friend so it can reach private data. A binary operator takes two arguments; a unary operator takes one.

class Point {
    int x, y;
public:
    Point(int a = 0, int b = 0) { x = a; y = b; }
    friend Point operator+(Point p, Point q);   // a + b -> operator+(a, b)
};
Point operator+(Point p, Point q) {
    return Point(p.x + q.x, p.y + q.y);
}

When to use which:

  • Member function: when the left operand is always an object of the class. =, [], (), -> must be members.
  • Non-member function: when the left operand is a built-in type or another class (e.g. 5 + obj, or cout << obj).

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 5 questions →