- Back to Home »
- Constructors
Posted by : Sushanth
Monday, 14 December 2015
Constructors:
Special member function of a class used to construct class objects.
Construction involves memory allocation and initialization for objects.
The name of the constructor is same name as its class.
For example:
class X {
public:
X(); // constructor for class X
};
Destructors:
Special member function of a class used to destroy class objects.
Destruction may involve cleanup and de-allocation of memory for objects.
A destructor is a member function with the same name as its class prefixed by a ~ (tilde). For example:
class X {
public:
// Constructor for class X
X();
// Destructor for class X
~X();
};
Restrictions:
- 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.
The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope.
If memory allocation is required for objects, constructors can explicitly call the new operator. During cleanup, a destructor may release objects allocated by the corresponding constructor. To release objects, use the delete operator.
Derived classes do not inherit or overload constructors or destructors from their base classes, but they do call the constructor and destructor of base classes. Destructors can be declared with the keyword virtual.
Free store is a pool of memory available for you to allocate (and deallocate) storage for objects during the execution of your program. The new and delete operators are used to allocate and deallocate free store, respectively.