Coupon Accepted Successfully!


Constructors and Destructors

In the previous chapter, we defined a separate member function for reading input values for data members. Using object, member function is invoked and data members are initialized. The programmer needs to call the function. C++ provides a pair of in-built special member functions called constructor and destructor. The constructor constructs the objects and destructor destroys the objects. In operation, they are opposite to each other. The compiler automatically executes these functions. The programmer does not need to make any effort for invoking these functions.

The C++ run-time arrangement takes care of execution of constructors and destructors. When an object is created, constructor is executed. The programmer can also pass values to the constructor to initialize member variables with different values. The destructor destroys the object. The destructor is executed at the end of the function when objects are of no use or go out of scope. It is optional to declare constructor and destructor. If the programmer does not define them, the compiler executes implicit constructor and destructor.

Constructors and destructors are special member functions. They decide how the objects of a class are created, initialized, copied, and destroyed. Their names are distinguished from all other member functions because their names are same as the class they belong to. The only difference is that destructor is preceded by a ~ (tilde) operator.

Constructors and destructors have many attributes as that of normal member functions. We can declare and define them within the class, or declare them within the class and define them outside; however, they have few unique characteristics.


If a class B has one or more constructors, one of them is invoked each time when we define an object b of class B. The constructor creates object b and initializes it. Constructors are also called when local or temporary objects of a class are created.



B() { }


Destructors are opposite to the constructor. The process of destroying the class objects created by constructors is done in destructor. The destructors have the same name as their class, preceded by a tilde (~). A destructor is automatically executed when object goes out of scope. It is also invoked when delete operator is used to free the memory allocated with class pointer. Similar to the constructor, it is not possible to define overloaded destructors and pass arguments to them. The class can have only one destructor. Destructors are called when these objects go out of scope.



~B() { }

Test Your Skills Now!
Take a Quiz now
Reviewer Name