Destructor in C++

Destructors in C++

A destructor in C++, as the name implies, is used to destroy the objects that have been created by a constructor. Like a constructor, the destructor in C++ is a member function whose name is the same as the class name but is preceded by a tilde (~). For example, the destructor for the class integer can be defined as shown below: ~integer() { } A destructor in C++ never takes any arguments nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program (or the block or the function as the case may be) to clean up the storage that is no longer accessible. It is a good practice to declare destructors in a program since it releases memory space for future use. Whenever new is used to allocate memory in the constructors, we should use delete to free that memory....

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: X.input(); invokes the member function input(), which assigns initial values to the data items of the object X. Similarly, the statement: A.getdata(100,299.95); 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...