What is Operator Overloading?
Operator overloading means defining how an existing C++ operator works with a user-defined type such as a class or struct.
Built-in types already know what operators mean:
int c = a + b;
But a class object does not automatically know what + means:
Complex c3 = c1 + c2;
The compiler needs a function that explains how to add two Complex objects.
Operator Overloading Is a Function
An overloaded operator is a function whose name starts with operator.
Basic form:
return_type operatorSymbol(parameters) {
// logic
}
For example:
Complex operator+(const Complex& other) const;
This means: when + is used with this object and another Complex object, run this function.
Complete Example
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(2, 3);
Complex c2(4, 5);
Complex c3 = c1 + c2; // same idea as c1.operator+(c2)
c3.display();
return 0;
}
Output:
6 + 8i
What Is Called Automatically?
When the compiler sees:
c1 + c2
it automatically searches for a matching overloaded operator+.
If operator+ is a member function, the call is like:
c1.operator+(c2);
If operator+ is a non-member function, the call is like:
operator+(c1, c2);
You normally write c1 + c2; the compiler performs the function call automatically.
Operator Overloading vs Function Overloading
Function overloading means multiple functions have the same name but different parameter lists.
void print(int x);
void print(double x);
Operator overloading is a special case where the function name is an operator function.
Complex operator+(const Complex& other);
You can often replace operator overloading with normal function names:
Complex c3 = c1.add(c2);
But c1 + c2 is shorter and more natural when the meaning is mathematically clear.
Viva Answer
Operator overloading allows an existing C++ operator to work with user-defined types. It is implemented by writing an operator function such as operator+. The compiler calls that function automatically when the operator is used with matching operands.
Quick Check
- Does operator overloading create new operators?
- What is the function name used to overload
+? - Is
c1 + c2closer toc1.operator+(c2)orc2.operator+(c1)for a member overload?