Skip to main content

Syntax of operator overloading

Write down the syntax of operator overloading for various cases.

Operator overloading is done by writing an operator function with the keyword operator followed by the operator symbol. General form:

return_type operator op (argument_list) { body }

1. Unary operator as member function (no argument)

return_type ClassName::operator-() { ... }     // used as  -a;  calls a.operator-()

2. Binary operator as member function (one argument)

return_type ClassName::operator+(ClassName b) { ... }   // c = a + b;  calls a.operator+(b)

The left operand is the invoking object; the right operand is the argument.

3. Unary operator as friend function (one argument)

friend return_type operator-(ClassName a);    // -a;  calls operator-(a)

4. Binary operator as friend function (two arguments)

friend return_type operator+(ClassName a, ClassName b);   // a + b

Needed when the left operand is a built-in type, e.g. 5 + obj.

5. Prefix and postfix increment/decrement

ClassName operator++();        // prefix  ++a
ClassName operator++(int);     // postfix a++  (dummy int distinguishes it)

6. Stream insertion and extraction (always non-member, usually friend)

friend ostream& operator<<(ostream &out, ClassName &obj);
friend istream& operator>>(istream &in, ClassName &obj);

7. Subscript operator

int& operator[](int index);

8. Assignment operator (must be a member)

ClassName& operator=(const ClassName &rhs);

Rules: =, [], () and -> can be overloaded only as member functions. At least one operand must be a user-defined type.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 5 questions →