Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to overload insertion(<<) ,extraction (>>) and assignment(=) operator for Time class object

C++ Code Example — Operator Overloading

ADVERTISEMENT

WAP to overload insertion(<<) ,extraction (>>) and assignment(=) operator for Time class object

Objective

Write a C++ program to overload the insertion (&lt;&lt;), extraction (&gt;&gt;), and assignment (=) operators.

Algorithm / Approach

  1. Create a Time class.
  2. Overload the assignment operator: Time operator=(Time t) as a member function.
  3. Declare friend functions for the extraction (operator&gt;&gt;) and insertion (operator&lt;&lt;) operators.
  4. Implement them to accept istream and ostream references respectively.
  5. In main(), use cin &gt;&gt; t and cout &lt;&lt; t directly on the object.
main.cpp
#include<iostream>
using namespace std;
class Time {
 int h, min,sec;
 public :
 Time(int a, int b,int c) {
  h = a;
  min = b;
  sec = c;
 }
 Time() {
  h = min = 0;
 }
 void show() {
  cout<< h<<" Hours "<< min;
  cout<<" minutes "<< sec<<" sec.\n";
 }
 Time operator=(Time t){
  h = t.h;
  min = t.min;
  sec = t.sec;
  return Time(h,min,sec);
 }
friend Time operator>>(istream &ob,Time &t);
friend Time operator<<(ostream &ob,Time &t);
};
Time operator>>(istream &ob,Time &t){
 cout<<"Enter Time ";
 ob>>t.h;
 ob>>t.min;
 ob>>t.sec;
}
Time operator<<(ostream &ob,Time &t){
 ob<< t.h<<"::"<< t.min;
 ob<<"::"<< t.sec<< endl;
}
int main() {
 Time t;
 cin>>t;
 cout<< t;
 t.show();
 Time t2,t3(5,10,30);
 t2 = t3;
 t3.show();
  return 0;
}

Expected Output

Enter Time 10 20 40
10::20::40
10 Hours 20 minutes 40 sec.
5 Hours  10 minutes 30 sec.

Explanation of the Program

  • By overloading &lt;&lt; and &gt;&gt;, you can print or read an entire complex object with a single standard cout or cin statement, just like you would with a basic integer.
  • These stream operators MUST be implemented as friend functions, not member functions. This is because the object on the left side of the operator is an ostream or istream object (like cout/cin), not your custom Time class object.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT