Naveen Said..
Constructors and Destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.
Constructor function gets invoked when an object of a class is constructed (declared) and destructor function gets invoked when the object is destructed (goes out of scope).
Like other member functions, constructors and destructors are declared within a class declaration. They can be defined inline or external to the class declaration. Constructors can have default arguments. Unlike other member functions, constructors can have member initialization lists.
The following restrictions apply to constructors and destructors:
- Constructors and destructors do not have return types nor can they return values.
- References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
- Constructors cannot be declared with the keyword virtual.
- Constructors and destructors cannot be declared static, const, or volatile.
- Unions cannot contain class objects that have constructors or destructors.
Use of Constructor and Destructor function of a class:
- Constructor function is used to initialize member variables to pre-defined values as soon as an object of a class is declared.
- Constructor function having parameters is used to initialize the data members to the values passed values, upon declaration.
- Generally, the destructor function is needed only when constructor has allocated dynamic memory.