OOPS - [C++ Constructor/Destructor of Class]

♠ Posted by Unknown in at 06:52

CONSTRUCTOR and DESTRUCTOR in Class

The need for initialization is even more common when you are working with objects. In fact, when applied to real problems, virtually every object you create will require some sort of initialization. To address this situation, C++ allows a “constructor function” to be included in a class declaration.  A class’s constructor is called each time an object of that class is crated. Thus, any initialization that need to be performed on an object can be done automatically by the constructor function.

A constructor function has the same name as the class of which it is a part and has no return type.

For global objects, an object’s constructor is called once, when the program first begins execution. For local objects, the constructor is called each time the declaration statement is executed.

The complement of a Constructor is the Destructor. This function is called when an object is destroyed. When you are working with objects, it is common to have to perform some actions when an object is destroyed. For example, an object that allocates memory when it is created will want to free that memory when it is destroyed. The name of a destructor is the name of its class, preceded by a ~.
A class’s destructor is called when an object is destroyed. Local objects are destroyed when they go out of scope. Global objects are destroyed when the program ends. It is not possible to take the address of either a constructor or a destructor.

For Example:

#include<iostream.h>
#include<conio.h>
class Sum
{
            int a, b;
 public:
            Sum();//Class Constructor Declaration
            void getdata();//Member Function Declaration
            int Answer(); //Member Function Declaration
            ~Sum();//Class Destructor Declaration
};

Sum::Sum()//Constructor Definition
{
 a=b=0;
 cout<<"Constructor is Invoked....."<<endl;
}

Sum::~Sum()//Destructor Definition
{
 cout<<"Destructor is Invoked....."<<endl;
}

void Sum::getdata()//Member Function Definition
{
 cout<<"Enter the First Value :";
 cin>>a;
 cout<<"Enter the SEcond Value :";
 cin>>b;
}

int Sum::Answer()//Member Function Definition
{return a + b;}

void main()
{
 clrscr();
 Sum ss;//Object Created Constructor is automatically Invoked
 ss.getdata();//Calling of member function
 int c = ss.Answer();
 cout<<"The Sum is :"<<c<<endl;
 getch();
}

0 comments:

Post a Comment