Constructor and Destructor in C++

Constructor:  A class constructor is a special member function of a class that is executed whenever we create new objects of that class. A constructor will have the exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables. Why you should define a constructor?

Uninitialized member fields have garbage in them. This creates the possibility of a serious bug (e.g., an uninitialized pointer, illegal 
values, inconsistent values ...). Characteristics of a constructor:
1. They should be declared in the public section
2. They have invoked automatically when the objects are created.
3. They cannot be inherited
4. They cannot be virtual

A constructor is similar to a function, but with the following differences.
1. No return type.
2. No return statement.
Types of Constructor
1. Default Constructor
2. Parameterized constructor
3. Copy constructor
4. Constructor with default arguments
5. Dynamic constructor

Destructor: A destructor is a special member function of a class that is executed whenever an object of its 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 the exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. The destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc. Whenever the object of the class is created, the constructor is called. The constructor is responsible for assigning initial values for all its data members. It has the same name as its class. Whenever an object is no longer needed, it has to be deleted from the memory, then we write a destructor for it. It takes the same name of their class preceded by a tilde (~).

Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment: