Constructors and Destructors in C++

Constructors and Destructors in C++

Constructors:

To initialize the data members of a class, Constructors are needed.  A Constructor function is a member function that is invoked automatically when an object of the class is created.  The name of a Constructor function is similar to that of the class name.  It is used to construct data members i.e. provide initial values to the data members of the class.  The Constructors may be invoked implicitly or explicitly.  Since data members are generally defined in private section in a class, they cannot be initialized like structure variables.  So, we need a member function to perform the same job and to invoke this function automatically by the compiler and not by the programmer, its name is kept similar to that of the class.

Consider the following example:

class sample
{
int x;
int y;
public:
sample( ){x=0; y=0;}
void put_ans( )
{
cout<<”x=”<<x;
cout<<”y=”<<y;
}
};

void main()
{
sample obj; //Constructor function is called
//and x,y receive value 0.
obj.put_ans();
}

In the above example, x and y are initialized to zero, when an object obj of class sample is created.  It is confirmed by printing the values through put_ans() function.  Hence x=0 and y=0 gets displayed on the screen.

A default constructor is one, which is invoked automatically and takes no arguments.  A parameterized constructor is one that can take arguments to initialize the data member.  A copy constructor is invoked when an object is initialized with some other object of the same class.

Destructors:

Destructor is a member function that has name similiar to that of class and precedes with a tilde (~) symbol.  A destructor function neither accepts any argument nor does it return any value.  The objects that are created using constructors are destroyed using destructors.  A destructor function is called automatically when the function goes out of scope and the program terminates.  If new operator is used in constructor for allocating memory, then delete operator is used in destructors for deallocating memory.

For example:

class sample{
int x;
int y;
public:
sample()
{
x = 0;
y = 0;
}
void put_ans()
{
cout<<”x = “<<x;
cout<<”y = “<<y;
}
~sample();  // Destructor declaration.
};
sample :: ~ sample()
{
cout << “Destructor function invoked !”;
}

The above example defines a constructor and destructor for the class named sample.  When the program is about to terminate the destructor function is called and “Destructor function invoked !” message gets displayed on the screen.