Overloading The Arithmetic Operators

# Introduction

Arithmetic oeprators are +, - , * and /.

# Overloading operators using friend functions

- When the operator does not modify its operands, the best way to overload the operator is via &&friend function**.

Example

class Cents { private: int m_nCents; public: Cents(int nCents) { m_nCents = nCents; } // Add Cents + Cents friend Cents operator+(const Cents &c1, const Cents &c2); int GetCents() { return m_nCents; } }; // note: this function is not a member function! Cents operator+(const Cents &c1, const Cents &c2) { // use the Cents constructor and operator+(int, int) return Cents(c1.m_nCents + c2.m_nCents); } int main() { Cents cCents1(6); Cents cCents2(8); Cents cCentsSum = cCents1 + cCents2; std::cout << "I have " << cCentsSum .GetCents() << " cents." << std::endl; return 0; }

# Overloading operators for operands of different types

- whenever we overload binary operators for operands of different types, we actually need to write two functions — one for each case.

Example

class Cents { private: int m_nCents; public: Cents(int nCents) { m_nCents = nCents; } // Overload cCents + int friend Cents operator+(const Cents &cCents, int nCents); // Overload int + cCents friend Cents operator+(int nCents, const Cents &cCents); int GetCents() { return m_nCents; } }; // note: this function is not a member function! Cents operator+(const Cents &cCents, int nCents) { return Cents(cCents.m_nCents + nCents); } // note: this function is not a member function! Cents operator+(int nCents, const Cents &cCents) { return Cents(cCents.m_nCents + nCents); } int main() { Cents c1 = Cents(4) + 6; Cents c2 = 6 + Cents(4); std::cout << "I have " << c1.GetCents() << " cents." << std::endl; std::cout << "I have " << c2.GetCents() << " cents." << std::endl; return 0; }