Wednesday 23 January 2013

Constructors in C++

C++ Constructor

Constructors are the special type of member function that initializes the object automatically when it is created. Compiler identifies that the given member function is a constructor by its name and return type. Constructor has same name as that of class and it does not have any return type.

Constructors are Basically of 3 types:-
1. Default Constructor: Constructor which does not take any arguments. And used to Initialize object data members with default values given by the programmer (say 0).
Syntax:
       class_name object_name; 
2. Parametrized Constructor: Constructors which takes arguments that can be helpful in initializing data members of class with these arguments..
Syntax:
       class_name object_name(argument1,argument2, ...); 
3. Copy Constructor: Constructors which are used to initialize object with the another object of same class. It Uses Reference Variables.
Syntax:
       class_name object_name(object);
 Note:
1. if a class contains parametrized constructor then its a mandatory to have a default constructor also.
2. copy constructor is need not be defined in class because it is already built when class is created. But it is a good programming practice to introduce copy constructor while making a class.
3. if default constructor is not defined in class then compiler itself provide a default constructor which initializes the data members with garbage value.

From the examples you will be more comfortable with Constructors.
..... ... .....   
class temporary
{
       private: 
          int x;
          float y;
       public:
          temporary(): x(5), y(5.5)        /* default Constructor  */
          {  
                     /* Body of constructor */
          }
          /* Remaining Body of Class*/ 
}
int main()
{
        temporary t1;
        .... ... ....
        return 0;
}            
Working of Constructor
In the above pseudo code, temporary() is a constructor. When the object of class temporary is created, constructor is called automatically and x is initialized to 5 and y is initialized to 5.5 automatically.
You can also initialize data member inside the constructor's function body as below. But, this method is not preferred.
temporary(){
   x=5;
   y=5.5;
}
/* This method is not preferred. */

Use of Constructor in C++

Suppose you are working on 100's of objects and the default value of a data member is 0. Initializing all objects manually will be very tedious. Instead, you can define a constructor which initializes that data member to 0. Then all you have to do is define object and constructor will initialize object automatically. These types of situation arises frequently while handling array of objects. Also, if you want to execute some codes immediately after object is created, you can place that code inside the body of constructor.
Ex: if u create a class for student, then the attributes can be name,roll no, marks, percentage, DOB etc. and if you created a physical instance of this class (i.e object) it will use garbage value unless it gets initialized. 

Constructor Example

/*Source Code to demonstrate the working of constructor in C++ Programming */
/* This program calculates the area of a rectangle and  displays it. */ 
 
#include <iostream>
using namespace std;
class Area
{
    private:
       int length;
       int breadth;

    public:
       Area(): length(5), breadth(2)  /* default Constructor */
       { 
       } 
       void GetLength()  
       { 
           cout<<"Enter length and breadth respectively: "; 
           cin>>length>>breadth;  
       }
       int AreaCalculation()  
       {   
           return (length*breadth);   
       }
       void DisplayArea(int temp)
       {
           cout<<"Area: "<<temp;
       }
};
int main()
{
    Area A1,A2(5,10);
    int temp;
    A1.GetLength();
    temp=A1.AreaCalculation();
    A1.DisplayArea(temp);
    cout<<endl<<"Default Area when value is not taken from user"<<endl;
    temp=A2.AreaCalculation();
    A2.DisplayArea(temp);
    return 0;
}

Explanation
In this program, a class of name Area is created to calculate the area of a rectangle. There are two data members length and breadth. A constructor is defined which initializes length to 5 and breadth to 2. And, we have three additional member functions GetLength(), AreaCalculation() and DisplayArea() to get length from user, calculate the area and display the area respectively.
When, objects A1 and A2 are created then, the length and breadth of both objects are initialized to 5 and 2 respectively because of the constructor. Then the member function GetLength() is invoked which takes the value of length and breadth from user for object A1. Then, the area for the object A1 is calculated and stored in variable temp by calling AreaCalculation() function. And finally, the area of object A1 is displayed. For object A2, no data is asked from the user. So, the value of length will be 5 and breadth will be 2. Then, the area for A2 is calculated and displayed which is 10.

Output
Enter length and breadth respectively: 6
7
Area: 42
Default Area when value is not taken from user
Area: 10

Constructor Overloading

Constructor can be overloaded in similar way as function overloading. Overloaded constructors have same name(name of the class) but different number of argument passed. Depending upon the number and type of argument passed, specific constructor is called. Since, constructor are called when object is created. Argument to the constructor also should be passed while creating object. Here is the modification of above program to demonstrate the working of overloaded constructors.
 
/* Source Code to demonstrate the working of overloaded constructors */
#include <iostream>
using namespace std;
class Area
{
    private:
       int length;
       int breadth;

    public:
       Area(): length(5), breadth(2)   // Constructor without no argument
       { }        
       Area(int l, int b): length(l), breadth(b)  // Constructor with two argument
       { }  
       void GetLength()
       {
           cout<<"Enter length and breadth respectively: ";
           cin>>length>>breadth;
       }
       int AreaCalculation()  
       { 
           return (length*breadth); 
       }
       void DisplayArea(int temp)
       {
           cout<<"Area: "<<temp<<endl;
       }
};
int main()
{
    Area A1,A2(2,1);
    int temp;
    cout<<"Default Area when no argument is passed."<<endl;
    temp=A1.AreaCalculation();
    A1.DisplayArea(temp);
    cout<<"Area when (2,1) is passed as arguement."<<endl;
    temp=A2.AreaCalculation();
    A2.DisplayArea(temp);
    return 0;
}
Explanation of Overloaded Constructors
For object A1, no argument is passed. Thus, the constructor with no argument is invoked which initializes length to 5 and breadth to 2. Hence, the area of object A1 will be 10. For object A2, 2 and 1 is passed as argument. Thus, the constructor with two argument is called which initializes length to l(2 in this case) and breadth to b(1 in this case.). Hence the area of object A2 will be 2.
Output
Default Area when no argument is passed.
Area: 10
Area when (2,1) is passed as arguement.
Area: 2

Default Copy Constructor

A object can be initialized with another object of same type. Let us suppose the above program. If you want to initialize a object A3 so that it contains same value as A2. Then, this can be performed as:
....
int main() {
   Area A1,A2(2,1);
   Area A3(A2);     /* Copies the content of A2 to A3 */
     OR, 
   Area A3=A2;      /* Copies the content of A2 to A3 */  
}
You might think, you may need some constructor to perform this task. But, no additional constructor is needed. It is because this constructor is already built into all classes.

if you have any Doubt then Leave comment. Your doubt will be resolved in next 24 hours.

No comments: