Why use Constructor and Destructor in C++
We have seen, so far, a few examples of classes being implemented. In all the cases, we have used member functions such as getdata() and setvalue() to provide initial values to the private member variables. For example, the following statement:
invokes the member function input(), which assigns initial values to the data items of the object X. Similarly, the statement:
passes the initial values as arguments to the function getdata(), where these values are assigned to the private variables of object A. All these ‘function call’ statements are used with the appropriate objects that have already been created. These functions cannot be used to initialise the member variables at the time of creation of their objects.
This means that we are not able to initialize a class type variable (object) when it is declared, much the same way as initialization of an ordinary variable. For example:
int p = 20;
float q = 20.5;
are the valid initialization statements for basic data type.
But, such statements have not happened with the objects we have so far studied.
It is therefore clear that some more features of classes need to be explored that would enable us to initialize the objects when they are created and destroy them when their presence is no longer necessary.
C++ provides a special member function called the constructor which enables an object to initialize itself when it is created. This is known as automatic initialization of objects. It also provides another member function called the destructor that destroys the objects when they are no longer required.