Constructor


Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors iitialize values to object members after storage is allocated to the object.
            class A
            {
             int x;
             public:
             A();  //Constructor
            };
    

Types of Contructor


Constructors are of three types : 1. Default Constructor 2. Parametrized Constructor 3.Copy COnstructor

Default Contructor


Default constructor is the constructor which doesn't take any argument. It has no parameter.
                class Cube
                {
                int side;
                public:
                Cube()
                 {
                  side=10;
                 }
                };
                
                int main()
                {
                Cube c;
                cout << c.side;
                } 
        
Output : 10

Parameterized Constructor


These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument.
                        class Cube
                        {
                         public:
                         int side;
                         Cube(int x)
                          {
                           side=x;
                          }
                        };
                        
                        int main()
                        {
                         Cube c1(10);
                         Cube c2(20);
                         Cube c3(30);
                         cout << c1.side;
                         cout << c2.side;
                         cout << c3.side;
                        } 
                
OUTPUT : 10 20 30

Copy Contructor


These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object. We will study copy constructors in detail later.

Destructor


Destructor is a special class function which destroys the object as soon as the scope of object ends. The destructor is called automatically by the compiler when the object goes out of scope. The syntax for destructor is same as that for the constructor, the class name is used for the name of destructor, with a tilde ~ sign as prefix to it.

Example


        class A
        {
        A()
         {
          cout << "Constructor called";
         }
        
        ~A()
         {
          cout << "Destructor called";
         }
        };
        
        int main()
        {
         A obj1;   // Constructor Called
         int x=1
         if(x)
          {
           A obj2;  // Constructor Called
          }   // Destructor Called for obj2
        } //  Destructor called for obj1