Constructor in C++


Constructor is a member function of the class.
It is called special member function because the name of the constructor is same as name of the class.
Constructor is used to construct the values for the data member of the class automatically when the object of class is created.
Like other member function there is no need to call constructor explicitly. It is invoked automatically each time the object of its class is created.
Every class having at least one constructor defined in it. If you do not define any constructor in the class then compiler will automatically create a constructor inside the class and assigns default value (0) to the data member of the class.
Constructor can be defined inside class as shown below:

     

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

Constructor can be defined outside class as shown below:


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

Now when you create an object of the class Rectangle as shown below:
Rectangle R1;
It will invoke constructor and assigns value 1 to its data member Height and Width.
The constructor that does not accept any argument is known as default constructor.
Following are important characteristics of Constructor:
(1) It is called automatically when object of its class is created.
(2) It does not return any value.
(3) It must be defined inside public section of the class.
(4) It can have default arguments.
(5) Inheritance of constructor is not possible.
(6) It can not virtual.
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. It is not possible to assign different values to the data members for the different object of the class using default constructor.

Download Projects


Download Programs