Create a class Time which stores the time in hours and minutes. when the object is created, the data members should be initialized with zero. Take the input through the constructors. Include a copy Constructor and destructor. WAP to call all the constructor and destructors.
Objective
Write a C++ program to demonstrate Default, Parameterized, and Copy Constructors, along with a Destructor.
Algorithm / Approach
- Create a
class Testrepresenting Time (hr, min). - Define a Default Constructor:
Test()that initializes hr and min to 0. - Define a Parameterized Constructor:
Test(int a, int b)that initializes hr and min to a and b. - Define a Copy Constructor:
Test(Test &a)that copies hr and min from an existing object. - Define a Destructor:
~Test(). - In
main(), create objects using all three constructors and observe the output.
main.cpp
#include<iostream>
using namespace std;
class Test {
int hr;
int min;
public :
Test() {
hr = 0;
min =0 ;
cout<<"Default Const. "<< endl;
}
Test(int a, int b) {
hr = a;
min = b;
cout<<"Param Const. "<< endl;
}
Test(Test &a) {
hr = a.hr;
min = a.hr;
}
~Test() {
cout<<"Destructor Called"<< endl;
}
void show() {
cout<< hr<<" : "<< min<< endl;
}
};
int main() {
Test t ;
t.show();
Test t2(12,30);
t2.show();
Test t3(t);
t3.show();
Test t4(t2);
t4.show();
return 0;
}
Expected Output
Default Const. 0 : 0 Param Const. 12 : 30 0 : 0 12 : 30 Destructor Called Destructor Called Destructor Called Destructor Called
Explanation of the Program
- Constructors are special class functions that are automatically called the exact moment an object is created in memory. They share the exact same name as the class and have no return type.
- Destructors (denoted by the
~tilde prefix) are automatically called the exact moment an object goes out of scope and is destroyed from memory. This is where you would typically write cleanup code (like closing files or freeing memory).
Complexity
Time Complexity
O(1)
Space Complexity
O(1)