Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Info

In C++, operator overloading is a feature that allows operators, such as +, -, *, /, and <<, to be overloaded with custom behavior for user-defined types. Operator overloading allows you to use the same syntax with your own classes as you would with built-in types, making your code more natural and intuitive.

Code Block
languagecpp
//  main.cpp
//  OperatorOverload
//  Text examnple modified by Kevin Roark on 3/31/23.
//  Please note that the class has been included on the main file - this is done for
//. For simplicity to understand the code 


#include <iostream>
using namespace std;
#include <iostream>
using namespace std;

// TimeHrMn class represents time with hours and minutes
class TimeHrMn {
public:
   TimeHrMn(int timeHours = 0, int timeMinutes = 0); // constructor
   void Print() const; // member function to print the time
   TimeHrMn operator+(TimeHrMn); // overloaded + operator for TimeHrMn operands
   TimeHrMn operator+(int); // overloaded + operator for TimeHrMn and int operands
private:
   int hours;
   int minutes;
};

// Overloaded + operator for TimeHrMn operands
TimeHrMn TimeHrMn::operator+(TimeHrMn pTime) {
   TimeHrMn timeTotal;
   
   timeTotal.hours   = hours   + pTime.hours;
   timeTotal.minutes = minutes + pTime.minutes;
   
   return timeTotal;
}

// Overloaded + operator for TimeHrMn and int operands
TimeHrMn TimeHrMn::operator+(int pHours) {
   TimeHrMn timeTotal;
   
   timeTotal.hours = hours + pHours;
   timeTotal.minutes = minutes; // Minutes stays the same
   
   return timeTotal;
}

// Constructor that initializes the time with hours and minutes
TimeHrMn::TimeHrMn(int pHours, int pMinutes) {
   hours  = pHours;
   minutes = pMinutes;
   
   return;
}

// Member function to print the time
void TimeHrMn::Print() const {
   cout << "H:" << hours << ", " << "M:" << minutes << endl;
}

int main() {
   TimeHrMn time1(3, 22);
   TimeHrMn time2(2, 50);
   TimeHrMn sumTime;
   
   sumTime = time1 + time2; // Invokes operator+ for TimeHrMn operands
   sumTime.Print();
   
   sumTime = time1 + 10;    // Invokes operator+ for TimeHrMn and int operands
   sumTime.Print();
   return 0;
}

...