- Asked 4/10
- 2073 Shrawan · 3 marks
- 2072 Kartik · 3 marks
- 2070 Asar · 4 marks
- 2068 Baisakh · 2 marks
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)
Related questions
- Binary and unary operator overloading · Object Oriented Programming, chapter 5
- City class with operator overloading · Object Oriented Programming, chapter 5
- Operator overloading: need and definition · Object Oriented Programming, chapter 5 · asked 3×
- Disadvantage of operator overloading · Object Oriented Programming, chapter 5
- Binary operator member function one argument · Object Oriented Programming, chapter 5
- Function overloading; new/delete average program · Object Oriented Programming, chapter 3
- Operators; conditional operator · Computer Programming, chapter 3
- Bus service use cases with elaboration · Object Oriented Analysis and Design, chapter 2