Operator Overloading in C++
Learning Objectives
- Define operator overloading in C++.
- Differentiate unary and binary operator overloading.
- Implement operator overloading using a class.
- Analyze the advantages and limitations of operator overloading.
Introduction
This lecture introduces operator overloading as a compile-time polymorphism feature in C++.
It enables built-in operators such as + and - to work with user-defined objects
in a meaningful and readable way.
Lecture Slides
Theory Explanation
Operator overloading allows an existing C++ operator to be redefined for class objects.
This makes programs more natural to write and easier to understand. For example, if
c1 and c2 are complex numbers, writing c1 + c2
is clearer than calling a separate function such as add(c1, c2).
Important: Operator overloading does not create new operators and does not
change precedence or associativity.
Example Program
complex_operator_overloading.cpp
#include <iostream>
using namespace std;
class Complex {
private:
int real;
int imag;
public:
Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
void display() const {
cout << real << " + " << imag << "i";
}
};
int main() {
Complex c1(2, 3), c2(4, 5);
Complex c3 = c1 + c2;
cout << "Sum = ";
c3.display();
return 0;
}
Explanation of the Program
- The class Complex stores the real and imaginary parts.
- The + operator is overloaded as a member function.
- The expression c1 + c2 returns a new object of type Complex.
- The program demonstrates binary operator overloading clearly and compactly.
Key Points to Remember
- Operator overloading is compile-time polymorphism.
- Not all operators can be overloaded.
- Overloaded operators should preserve intuitive meaning.
- Complex numbers are a classic example for teaching binary operator overloading.
Viva Questions
- What is operator overloading in C++?
- Why is it called compile-time polymorphism?
- What is the difference between unary and binary operators?
- Can all operators be overloaded? Give examples.
- Why is the Complex class suitable for operator overloading?
Practice / Assignment Questions
| Question Type | Question |
|---|---|
| Short Answer | Define operator overloading and write its general syntax. |
| Long Answer | Design and implement a class to overload a binary operator and justify its design. |
| Programming Task | Write a C++ program to overload the - operator for a Complex class. |
References
- E. Balagurusamy, Object Oriented Programming with C++.
- Herbert Schildt, C++: The Complete Reference.
- Bjarne Stroustrup, The C++ Programming Language.
Comments
Post a Comment