1In C++, we can change the way operators work for user-defined types like objects and structures. This is known as operator overloading. For example,
2
3Suppose we have created three objects c1, c2 and result from a class named Complex that represents complex numbers.
4
5Since operator overloading allows us to change how operators work, we can redefine how the + operator works and use it to add the complex numbers of c1 and c2 by writing the following code:
6
7result = c1 + c2;
8instead of something like
9
10result = c1.addNumbers(c2);
11This makes our code intuitive and easy to understand.
12
13Note: We cannot use operator overloading for fundamental data types like int, float, char and so on.
14
15Syntax for C++ Operator Overloading
16To overload an operator, we use a special operator function.
17
18class className {
19 ... .. ...
20 public
21 returnType operator symbol (arguments) {
22 ... .. ...
23 }
24 ... .. ...
25};
1std::ostream& operator<<(std::ostream& out, const Course& course)
2{
3 out << course.getName(); // for example
4 return out;
5}
6
1// money.h -- define the prototype
2class Money
3{
4 public:
5 Money & operator += (const Money &rhs);
6}
7
8// money.cpp -- define the implementation
9Money& Money :: operator += (const Money &rhs)
10{
11 // Yadda Yadda
12
13 return *this;
14}
1#include <iostream>
2#include <string>
3
4class Car
5{
6private:
7 std::string m_make;
8 std::string m_model;
9
10public:
11 Car(const std::string& make, const std::string& model)
12 : m_make{ make }, m_model{ model }
13 {
14 }
15
16 friend bool operator== (const Car &c1, const Car &c2);
17 friend bool operator!= (const Car &c1, const Car &c2);
18};
19
20bool operator== (const Car &c1, const Car &c2)
21{
22 return (c1.m_make== c2.m_make &&
23 c1.m_model== c2.m_model);
24}
25
26bool operator!= (const Car &c1, const Car &c2)
27{
28 return !(c1== c2);
29}
30
31int main()
32{
33 Car corolla{ "Toyota", "Corolla" };
34 Car camry{ "Toyota", "Camry" };
35
36 if (corolla == camry)
37 std::cout << "a Corolla and Camry are the same.\n";
38
39 if (corolla != camry)
40 std::cout << "a Corolla and Camry are not the same.\n";
41
42 return 0;
43}