Constructor & Destructor in C++

In this tutorial we will study and understand the concept of Constructor & Destructor in C++. Before starting with this tutorial it will be helpful if you know the concept of Classes and Objects in C++

constructor and destructror in cpp

The Class Constructor

A class constructor is a special member function of a class that is executed whenever we create new objects of that class. Every time an instance of a class is created the constructor method is called.
The constructor has the same name as the class and it doesn’t return any type(not even void).
Constructors can be very useful for setting initial values for certain member variables.
Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution :: operator. A constructor can never be private.

Constructor Declaration & Definition
Types of Constructors:
  • Default Constructor
  • Parametrized Constructor
  • Copy Constructor
Default Constructor

Default constructor is the constructor which doesn’t take any argument. It has no parameter.In this case, as soon as the object is created the constructor is called which initializes its data members. If you don’t create a default constructor, the compiler provides a default constructor by default.

Run Online

Constructor Called
Parameterized Constructor

These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument.

Run Online

Copy Constructor

These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object. We will study copy constructors in detail later.

Run Online

The Class Destructor

A destructor is a special member function of a class that is executed whenever an object of it’s class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.

A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.

Run Online

Destructor Called
Watch it on YouTube

Leave a Reply

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