The Constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created.
Example:
class integer
{
int m,n;
public:
integer(void); //declaration of constructor
};
integer::integer(void) //definition of constructor
{
m=0;n=0;
}
Characteristics of constructors:
- They should be declared in the public section
- They are invoked automatically when the objects are created.
- They do not have return types, not even void.
- They cannot be inherited
- They can have default arguments
The constructor that can take arguments is called parameterized constructor.
//C++ program as example for constructors
#include
class sample
{
int m,n;
public:
sample(int, int);
void display(void)
{
cout<< “value of m is=” <<m<< “\n”;
cout<< “value of n is=” <<n<< “\n”;
}
};
sample::sample(int x, int y)
{
m=x; n=y;
}
main()
{
sample s1(0,100);
sample s2=sample(25,75);
cout<< “\nValues in Object1” << “\n”;
s1.display();
cout<< “\nValues in Object2” << “\n”;
s2.display();
}
DESTRUCTORS:
A destructor is used to destroy the objects that have been created by a constructor. It never takes any argument nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program to clean up storage.
//program that illustrates Destructor
#include
int count=0;
class alpha
{
public:
alpha()
{
count++;
cout<< “\n No. of objects created:” <<count;
}
~alpha() //destructor
{
cout<< “\nNo. of objects destroyed:”<<count;
count–;
}
};
main()
{
alpha a1,a2,a3,a4;
alpha a5;
alpha a6;
}