Parameterized Constructor


Disadvantage of default constructor is that each time an object is created it will assign same default values to the data members of the class.
However sometimes it is required to assign different values to the data members for the different object of the class. This can be accomplished using the concept of parameterized constructor.
The constructor that accepts parameters as an argument is called Parameterized constructor.
Parameterized Constructor can be defined inside class as shown below:

     

Class Rectangle
{
int Height, Width;
public:
Rectangle (int h, int w)
{
Height = h;
Width = w;
}
}

Parameterized Constructor can be defined outside class as shown below:

Class Rectangle
{
int Height, Width;
public:
Rectangle (int h, int w);
}
Rectangle :: Rectangle (int h, int w)
{
Height = h;
Width = w;
}

Now when you create an object of the class Rectangle as shown below:
Rectangle R1;
It will not invoke parameterized constructor but it will invoke default constructor and assigns default value 0 to its data member Height and Width.
In order to invoke parameterized constructor we need to pass arguments while creating object. We can pass arguments using two different methods:
(1) Implicit:
Rectangle R1 (10, 20);
It will assign value of 10 to Height and value of 20 to Width.
(2) Explicit:
Rectangle R2 = Rectangle (30, 40);
It will assign value of 30 to Height and value of 40 to Width.

Download Projects


Download Programs