Constructor and Destructor in C++


A constructor is a special function of a class which is executed whenever the object is created of that class. Every class must have a constructor and a destructor function to allocate and delete the memory for that object. Unlike other class member functions, constructor is a function which is executed at first when the object is being created.

Constructor function can be overloading but it cannot return any value and constructor function must be the class name.


Destructor function is executed when the object is destroyed. Destructor function deletes all memory spaces that were allocated for this object. Like constructor function, destructor function should not have the return type. Destructor function also the same name as class name with ~ sign append.

Sample Class

#include <iostream>

using namespace std;

class CRect {


int width, height;



CRect(int w, int h);

void setValue(int, int);

int area() { return width * height; }

~CRect(){ cout<<"Destructor...\n"; }           




width = height = 0;


CRect::CRect(int a, int b)


width = a;

height = b;


void CRect::setValue(int x, int y)


width = x;

height = y;


int main()


CRect RectA (5,6);

CRect RectB;


cout<<"Area of Rectangle A: " <<RectA.area()<<endl;

cout<<"Area of Rectangle B: " <<RectB.area()<<endl;

return 0;



Area of Rectangle A: 30
Area of Rectangle B: 56

In above sample example CRect() and CRect(int w, int h) both are constructor functions. And ~Rect() is a destructor function.