- 2068 Chaitra · 2 marks
Binary operator member function one argument
Short answer
With a member function, the left operand is the calling object (passed implicitly via this pointer), so only the right operand is required as an explicit parameter. a+b becomes a.operator+(b).
Why does the overloading of a binary operator with a member function require only one argument?
A binary operator has two operands, for example a + b. When it is overloaded as a member function, the left operand is the object that calls the function, and it is passed implicitly through the this pointer. So only the right operand needs to be passed explicitly as an argument.
class Complex {
float re, im;
public:
Complex operator+(Complex b) { // one argument: right operand
Complex r;
r.re = re + b.re; // re is this->re (left operand a)
r.im = im + b.im;
return r;
}
};
// c = a + b; is interpreted as c = a.operator+(b);
Here a is the invoking object (available as this), and b is the only explicit argument. In contrast, a friend (non-member) function has no this pointer, so it needs two arguments for a binary operator.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Binary and unary operator overloading · Object Oriented Programming, chapter 5
- City class with operator overloading · Object Oriented Programming, chapter 5
- Default argument and overloading program · Object Oriented Programming, chapter 3
- Overloading via member and non-member function · Object Oriented Programming, chapter 5
- Function overloading; new/delete average program · Object Oriented Programming, chapter 3
- Syntax of operator overloading · Object Oriented Programming, chapter 5 · asked 4×
- Why DTFS uses only one period · Signals and Systems, chapter 2
- T/F: tower height function of voltage only · Transmission and Distribution System Design, chapter 4 · asked 2×