Categories: C++

Examples of Operator Overloading in C++

Let’s see examples of operator overloading in C++ for various types of operators.

Examples:
1) Add given timestamps by overloading + operator
#include <iostream>
using namespace std;

class Time {
private:
 int HR, MIN, SEC;

 // Defining functions
public:
 // Functions to set the time
 // in the Time class template
 void setTime(int x, int y, int z)
 {
  HR = x;
  MIN = y;
  SEC = z;
 }

 // Function to print the time
 // in HH:MM:SS format
 void showTime()
 {
  cout << endl
   << HR << ":" << MIN << ":" << SEC;
 }

 // Function to normalize the resultant
 // time in standard form
 void normalize()
 {
  MIN = MIN + SEC / 60;
  SEC = SEC % 60;
  HR = HR + MIN / 60;
  MIN = MIN % 60;
 }

 // + Operator overloading
 // to add the time t1 and t2
 Time operator+(Time t)
 {
  Time temp;
  temp.SEC = SEC + t.SEC;
  temp.MIN = MIN + t.MIN;
  temp.HR = HR + t.HR;
  temp.normalize();
  return (temp);
 }
};

// Driver code
int main()
{
 Time t1, t2, t3;
 t1.setTime(3, 49, 30);
 t2.setTime(7, 10, 34);

 // Operator overloading
 t3 = t1 + t2;

 // Printing results
 t1.showTime();
 t2.showTime();
 t3.showTime();

 return 0;
}

setTime() function is used to set HR, MIN and SEC values.

showTime() function displays the time in a specific format (HH:MM:SS).

We add the seconds, minutes, and hours separately to get the new time value.

Output:
3:49:30
7:10:34
11:0:4
2) Overloading Relational Operator :
#include <iostream>
using namespace std;

class Student{
    int feet = 0; //can be b/w 0 & infinity
    int inches = 0; // can be b/w 0 & 12
    
    public:
    void getHeight(int f, int i){
        feet = f;
        inches = i;
    }

    // const and & added check explanation above(Before code) why
    bool operator > (const Student& s2)
    {
        if(feet > s2.feet)
            return true;
        
        else if(feet == s2.feet && inches > s2.inches)
            return true;
         
        return false;
    }
};

int main()
{
    Student s1,s2;
    
    s1.getHeight(5,10);
    s2.getHeight(6,1);
    
    if(s1 > s2)
        cout << "Student 1 is taller" << endl; else if(s2 > s1)
        cout << "Student 2 is taller" << endl;
    else
        cout << "Both have equal height" << endl;
    

    return 0;
}

Here we are Overloading > i.e. greater than operator.

Output:
Student 2 is taller
3)  Overloading << Operator
#include <iostream>

class Point
{
private:
    double m_x{};
    double m_y{};
    double m_z{};

public:
    Point(double x=0.0, double y=0.0, double z=0.0)
      : m_x{x}, m_y{y}, m_z{z}
    {
    }

    friend std::ostream& operator<< (std::ostream& out, const Point& point);
};

std::ostream& operator<< (std::ostream& out, const Point& point)
{
   
    out << "Point(" << point.m_x << ", " << point.m_y << ", " << point.m_z << ')'; // actual output done here

    return out; // return std::ostream so we can chain calls to operator<<
}

int main()
{
    const Point point1{2.0, 3.0, 4.0};

    std::cout << point1 << '\n';

    return 0;
}

Since operator<< is a friend of the Point class, we can access Point’s members directly.

Output:
Point(2, 3, 4)
4) Copy Constructor & Assignment Operator:

Copy constructor and Assignment operator are similar, as they are both used to initialize one object using another. However, there are some fundamental differences between them:

  • The assignment operator is used to copy values from one object to another that already exists.
  • In contrast, the Copy constructor is a particular constructor that creates a new object from an existing one.
#include <iostream>
#include <stdio.h>
using namespace std;

class Test {
public:
 Test() {}
 Test(const Test& t)
 {
  cout << "Copy constructor called " << endl;
 }

 Test& operator=(const Test& t)
 {
  cout << "Assignment operator called " << endl;
  return *this;
 }
};

// Driver code
int main()
{
 Test t1, t2;
 t2 = t1;
 Test t3 = t1;
 getchar();
 return 0;
}
Output:
Assignment operator called 
Copy constructor called 

Note: also read about Operator Overloading in C++

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

4 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

4 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

10 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

10 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

10 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

11 months ago