WAP to overload insertion(<<) ,extraction (>>) and assignment(=) operator for Time class object
Objective
Write a C++ program to overload the insertion (<<), extraction (>>), and assignment (=) operators.
Algorithm / Approach
- Create a
Timeclass. - Overload the assignment operator:
Time operator=(Time t)as a member function. - Declare
friendfunctions for the extraction (operator>>) and insertion (operator<<) operators. - Implement them to accept
istreamandostreamreferences respectively. - In
main(), usecin >> tandcout << tdirectly 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
<<and>>, you can print or read an entire complex object with a single standardcoutorcinstatement, just like you would with a basic integer. - These stream operators MUST be implemented as
friendfunctions, not member functions. This is because the object on the left side of the operator is anostreamoristreamobject (like cout/cin), not your custom Time class object.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)