Constructor and Destructor in C++

Constructor

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

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 {

private:

int width, height;

public:

CRect();

CRect(int w, int h);

void setValue(int, int);

int area() { return width * height; }

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

};

CRect::CRect()

{

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;

RectB.setValue(7,8);

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

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

return 0;

}

Output

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

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

Next Recommended Reading OOPs Dynamic Binding Program Using C++