C++ : Constructors And Destructors 3

Parameterized constructors

Parameterized Constructors are special functions which if present automatically get executed whenever an object of a class is declared with parameters.

Example:

employee e;//default cons will get invoked
employee e1(101,”abc”,50000);//para cons gets invoked

student s; // default cons will get invoked
student s1(100,”abc”,90);//para cons gets invoked

bank b(1001,”Abc”,15000);//para cons gets invoked

Properties

1. Name of the parameterized constructors function is exactly same as that of the class.
2. It has no return type not even void.
3. If present it automatically gets executed whenever an object of a class is declared with parameters.
4. It cannot be invoked using an object of the class.
5. It is generally used to initialize the data elements of an object by the arguments passed at the time of declaration.
6. There can be number of parameterized constructors in the class.
7. Parameterized constructors can be overloaded.

The parameterized constructor gets invoked in two ways.

1. Implicit calling

2. Explicit calling

Implicit calling

Implicit calling is the default process. Whenever an object of a class is declared with parameters the parameterized constructor automatically gets called.
Example:
Student s(101,”hello”,90);

Explicit calling

In explicit calling we have to mention the name of the constructor to be invoked.
Example:
student s=student(101,”hello”,90);