What are Constructors and Destructors in C++ ?
![]() Don't want to miss a single bit? Subscribe By Email for Daily Jobs |
A constructor constructs an object i.e. it initializes the objects internal data members as well as it may allocate resource (memory, files, sockets, etc). The constructor has the same name as the class name and cannot have a return type not even void.
A constructor can take multiple arguments as its parameters. A class can have multiple constructors i.e. a constructor can be overloaded. Whenever an object of a class is created it calls a constructor by default which is responsible for initializing the object. By default every class has a default constructor which is a constructor with no arguments. However once you provide a constructor to a class then the default constructor does not exist. e.g.
class Stack
{
int size;
int top;
int arr [];
Stack(int a) //constructor of the class
{
size = a;
arr = new int[size];
}
};
The destructor is the last member function called in the lifetime of a class object. Its job is to free the resources that an object is holding. A class can have no more than a single destructor. The name of the destructor is ~ classname (). Like a constructor, a destructor cannot have a void return type.
e.g. ~Stack () //destructor
{
delete [] arr;
}
Related Articles
- What is a Copy Constructor in C++ ? Give an example
- What is Multiple Inheritance in C++ ? Explain with an example
- Can You write your own exeptions in Java ?
- What is ‘this’ Pointer (object) in C++
- What are classes ? How are they defined ?


