Thursday 4 September 2014

CONSTRUCTOR AND DESTRUCTOR

CONSTRUCTOR

 
In C++ it is not allowed to initialize a variable directly in the class so what.
 
 we do, We use the concept of constructor to initialize the variables.
 
CONSTRUCTOR PROPERTIES
  1. Constructor name is same of its class.
  2. It has no return type.
  3. It is always declared in the public section of the class.
  4. As the first object of the class created ,Constructor get invoked.
  5. Constructor can be overloaded. 
Constructor is of three types
  • Constructor with no arguments
  • Constructor with arguments(Parameterized Constructor)
  • Copy constructor
Copy Constructor
If we want to use any value again and again then instead of passing that value again and again we pass the object which contains that particular value.
 
DESTRUCTOR
 
Destructor are quite similar to constructor but their main objectives is to destroy the object. Destructor properties are same but their declared with the help of (~) tilde sign.Their main objectives is to take memory back from the objects which were created during the design of programs.
 
 
 
Now We take a example in which we will use all of three constructors and these are Constructor with no arguments , Constructor with arguments Copy constructor and also Destructor. Lets see
 
#include<iostream.h>
#include<conio.h>
class test
{
int a;
public:
 
test()                                           //Constructor with no arguments
{
a=100;
}
 
test(int x)                                  //Constructor with arguments
{
a=x;
}
test(test &t)                              //Copy constructor
{
a=t.a;
}
void show()
{
cout<<a;
}
~test()                                      //Destructor
{
cout<<"object destroyed";
}
};
void main()
{
test t;
t.show();
test t1(100);
t1.show();
test t2(t1);
t2.show();
getch();
}
 
 
 
 


No comments:

Post a Comment