Cpp Tutorial: Introduction to Constructor and Destructor in C++

In this chapter we shall look at below topics
1. Introduction
2. Constructor and its properties
3. Destructor and its properties

1. Introduction 

In the previous chapter we have seen, to initialize the data members we used a helper method like “setters” and “getters” after creating an object. But with the help of constructors we can do it while declaring an object.
Constructor and destructors are special member functions whose name is same as the class name. Constructor is called before an object is created, and destructor will be called just before an object is getting out of scope.
Hence if you want to initialize an object, we can take use of constructor, and destructor to un initialize or to free the memory.

2. Constructor and its properties

Constructor syntax:
	<class_name>(<argument_list>) 
	{
		//statements
	}
Constructor properties:
1. Name of constructor should be same as class name
2. Constructor cannot return any value
3. Constructor can be overloaded
4. A constructor without any arguments are called as default constructor
5. Constructor are called implicitly when an object is created. It can also be called explicitly.
6. Constructor cannot be virtual

3. Destructor and its properties

Destructor Syntax:
~<class_name>()
{
//statements
}
Destructor properties:
1. Name of destructor should be same as class name preceded by tilde ~.
2. Destructor will not accept any parameters.
3. Destructor will be automatically executed when an object goes out of scope.
4. They don’t return any values
5. Usually used to free dynamically allocated memory.
6. Destructor can be virtual
7. Destructor cannot be overloaded and destructor will not take any parameter.
8. It should be declared in public section.

Simple example of constructor and destructor:

When there are multiple objects are created to a class, the objects are destroyed in reverse order.
Example:
#include<iostream>
using namespace std;

int objectCount = 0;

class ConstructorDestructorDemo
{

	public:
	
	ConstructorDestructorDemo ()
	{
		objectCount++;
		cout<<"The object "<< objectCount <<" Constructor is called"<<endl;
	}
	
	~ ConstructorDestructorDemo ()
	{
		cout<<"The object "<< objectCount <<" destructor is called"<<endl;
		objectCount--;
	}

};

int main()
{
ConstructorDestructorDemo d1;
ConstructorDestructorDemo d2;
ConstructorDestructorDemo d3;
ConstructorDestructorDemo d4;

return 0;
}

Output:

The object 1 Constructor is called
The object 2 Constructor is called
The object 3 Constructor is called
The object 4 Constructor is called
The object 4 destructor is called
The object 3 destructor is called
The object 2 destructor is called
The object 1 destructor is called
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *