Constructor
Objective: Design and implement a class Time which has constructor and destructor
member function. You class should use multiple constructors and a destructor.
Define class for Time considering the followings:
a. Enlist data members and methods with access specifies.
b. At least one member function and data members should be constant
#include <iostream>
using namespace std;
class Time
{
public:
Time();
Time(int s, int m, int h);
~Time();
void Display() const;
void AddHour();
int GetSec() const { return sec; }
int GetMins() const { return mins; }
int GetHours() const { return hours; }
private:
int sec;
int hours;
int mins;
const int INIT = 0;
};
Time::Time()
{
sec = INIT;
mins = INIT;
hours = INIT;
}
Time::Time(int s, int m, int h)
{
if (s < 0) sec = 0;
else sec = s % 60;
if (m < 0) m = 0;
else mins = m % 60;
if (h < 0) h = 0;
else hours = h % 24;
}
void Time::Display() const
{
cout << hours / 10 << hours % 10 << ":" << mins / 10 << mins % 10 << ":" << sec / 10 << sec % 10 << endl;
}
void Time::AddHour()
{
hours = (hours + 1) % 24;
}
Time::~Time()
{
cout << "Time destructor" << endl;
}
int main()
{
Time t1;
Time t2(225, 125, 100);
t1.Display();
t2.Display();
t1.AddHour();
t2.AddHour();
t1.Display();
t2.Display();
system("pause");
return 0;
}
Comments
Leave a comment