Operator Overloading
Custom operators for classes
Interview Relevant: C++ specific feature
Operator Overloading
Define custom behavior for operators.
Code Examples
Overloading various operators.
cpp
1class Complex {
2 double real, imag;
3
4public:
5 Complex(double r = 0, double i = 0) : real(r), imag(i) {}
6
7 // Binary + as member
8 Complex operator+(const Complex& other) const {
9 return Complex(real + other.real, imag + other.imag);
10 }
11
12 // Unary -
13 Complex operator-() const {
14 return Complex(-real, -imag);
15 }
16
17 // Comparison
18 bool operator==(const Complex& other) const {
19 return real == other.real && imag == other.imag;
20 }
21
22 // Subscript
23 double& operator[](int i) {
24 return i == 0 ? real : imag;
25 }
26
27 // Function call
28 double operator()() const {
29 return sqrt(real*real + imag*imag);
30 }
31
32 // Prefix ++
33 Complex& operator++() {
34 ++real;
35 return *this;
36 }
37
38 // Postfix ++
39 Complex operator++(int) {
40 Complex temp = *this;
41 ++real;
42 return temp;
43 }
44};
45
46Complex a(1, 2), b(3, 4);
47Complex c = a + b; // (4, 6)
48Complex d = -a; // (-1, -2)
49double mag = c(); // magnitude