WAP to convert the 12 hrs time format to 24 hrs time format
Objective
Write a C++ program to overload the typecast operator to convert a 12-hour Time object into a 24-hour Time object.
Algorithm / Approach
- Create a destination
class Time24. - Create a source
class Time12. - Inside
Time12, define a typecast operator:operator Time24(). - Inside the operator, calculate the 24-hour equivalent (e.g., add 12 if "pm") and return a
Time24object. - In
main(), cast the object:t2 = (Time24)t;.
main.cpp
#include<iostream>
#include<string.h>
using namespace std;
class Time24 {
public :
int h, min;
void show() {
cout<< h<<" : "<< min<< endl;
}
};
class Time12 {
public :
int hr, m;
string loc;
Time12(int a, int b, string l) {
hr = a;
m = b;
loc = l;
}
void show() {
cout<< hr<<" :: "<< m<<" :: ";
cout<< loc<< endl;
}
operator Time24() {
Time24 ob;
ob.h = hr;
ob.min = m;
if(loc=="pm") {
ob.h = ob.h+12;
}
return ob;
}
};
int main() {
Time12 t(10,15,"pm") ;
Time24 t2;
t2 = (Time24)t;
t.show();
t2.show();
return 0;
}
Expected Output
10 :: 15 :: pm 22 : 15
Explanation of the Program
- C++ allows you to write custom Typecast Operators to teach the compiler how to convert your class into a completely different class or data type.
- Because the typecast operator
operator Time24()is a member of the source class (Time12), it knows exactly how to read its own 12-hour data, package it up, and morph itself into a validTime24object.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)