Operator Overloading
Introduction
Operator overloading allows operators (+, -, *, etc.) to work with user-defined types (classes).
Definition
Operator overloading: giving special meaning to an operator for a class.
Code Example
class Complex {
int r,i;
public:
Complex(int a,int b):r(a),i(b){}
Complex operator+(Complex c){ return Complex(r+c.r, i+c.i); }
void show(){ cout<<r<<"+" <<i<<"i"; }
};
int main(){ Complex a(1,2),b(3,4); Complex c=a+b; c.show(); }MCQ Practice
1. Operator overloading is:
- Compile-time polymorphism
- Run-time polymorphism
- Inheritance
- None
Answer: compile-time.
2. Which cannot be overloaded?
- :: (scope resolution)
- +
- -
- []
Answer: ::.
3. Overloaded operators must have:
- At least one user-defined operand
- Both built-in
- No operands
- None
Answer: user-defined operand.
4. Operator overloading improves:
- Readability
- Speed
- Memory
- None
Answer: readability.
5. Friend functions can overload operators:
- Yes
- No
- Only +
- Only -
Answer: yes.
Quick Revision
- Overload operators for classes.
- Compile-time polymorphism.
- Cannot overload ::, ., .*, sizeof.