What are Constructors and Destructors in C++ ?

October 28, 2007 · Filed Under C++ Questions, Placement Questions 



Don't want to miss a single bit? Subscribe By Email for Daily Jobs

Enter your email address :

All the latest from JobsAdda on Jobsadda.com delivered to your mailbox everyday.

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


Get Latest JobsAdda.com Jobs, news & updates  via Email