- 2069 Chaitra · 3 marks
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, orcout << obj).
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Function overloading; new/delete average program · Object Oriented Programming, chapter 3
- Binary operator member function one argument · Object Oriented Programming, chapter 5
- Default arguments and function overloading · Object Oriented Programming, chapter 3 · asked 5×
- Function overriding versus overloading · Object Oriented Programming, chapter 6 · asked 2×
- Need of template; function template overloading · Object Oriented Programming, chapter 9
- Static data member and member function · Object Oriented Programming, chapter 4 · asked 3×
- Global vs local; & and * operators · Computer Programming, chapter 3
- Operators and expected energy in a well · Electrical Engineering Material, chapter 1
- Need for non-uniform quantization; SQNR of DM · Communication Systems, chapter 4 · asked 2×
- Is recursion slow; recursive vs non-recursive · Data Structure and Algorithm, chapter 5