Differentiate between Constructor and Destructor functions giving suitable example using a class in C++. When does each of them execute?
Constructor |
Destructor |
|
Purpose |
Constructor is used to initialize the instance of a class. |
Destructor destroys the objects when they are no longer needed. |
When Called |
Constructor is Called when new instance of a class is created. |
Destructor is called when instance of a class is deleted or released. |
Memory Management |
Constructor allocates the memory. |
Destructor releases the memory. |
Arguments |
Constructors can have arguments. |
Destructor can not have any arguments. |
Overloading |
Overloading of constructor is possible. |
Overloading of Destructor is not possible. |
Name |
Constructor has the same name as class name. |
Destructor also has the same name as class name but with (~) tiled operator. |
Syntex |
ClassName(Arguments) |
~ ClassName() |
Example:
Class Exam
{
int Eno; float Marks;
public:
Exam() ...Constructor
{
Eno=1; Marks = 100;
cout<<'Constructor executed...'<<endl;
}
void Show()
{
cout<<Eno<<'#'<<Marks<<endl;
}
~Exam() ...Destructor
{
cout<<'Exam Over'<<endl;
}
};
void main()
{
Exam E; ...Executes constructor
E.Show();
} ...Executes Destructor