Objects need to initialize the variables or assign the dynamic memory to them
during their
creation to become operative and to avoid the returning unexpected values during
execution.
A D V E R T I S E M E N T
To avoid this, a class can include special function "constructor",
which is been automatically called when the new object of the class is created. The
constructor function should have same name as that of the class, and cannot have the
return type not even the void.
Here we have implemented the CRectangle class including the constructor:
// example: class constructor
#include <iostream>
using namespace std;
class CRectangle
{
int width, height;
public:
CRectangle (int,int);
int area ()
{
return
(width*height);
}
};
CRectangle::CRectangle (int a, int b)
{
width = a;
height = b;
}
Here the constructor initializes the values of x and y with parameters which are passed
to it.
The Arguments to Constructor
Look at the way in which arguments are passed to constructor, they are passed at the
moment the objects of the class are created:
CRectangle rect (3,4);
CRectangle rectb (5,6);
As regular member functions, Constructors cannot be called explicitly
They are executed only when the new object of the class is been created.
There is neither prototype nor constructor declaration been done and neither
includes return value; nor void.
Destructors
A destructor fulfills opposite functionality. This is automatically been called when the
object is been destroyed, because the scope of existence has finished off or due
the reason that it is object which is dynamically assigned and it is released using
delete operator.
A destructor should have same name as that of class, but prefixed with tilde sign
(~) and it should not return any value.
Use of the destructors is suitable especially when the object assigns the dynamic memory
during lifetime and at the moment the object is destroyed we want to free the memory
which was allocated to the object.
// example on constructors and destructors
#include <iostream>
using namespace std;
class CRectangle
{
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area ()
{
return (*width * *height);
}
};
CRectangle::CRectangle (int a, int b)
{
width = new int;
height = new int;
*width = a;
*height = b;
}