Coupon Accepted Successfully!


Overloading Constructors (Multiple Constructors)

Similar to functions, it is also possible to overload constructors. In the previous examples, we declared single constructors without arguments and with all arguments. A class can contain more than one constructor. This is known as constructor overloading. All constructors are defined with the same name as the class they belong to. All the constructors contain different number of arguments. Depending upon the number of arguments, the compiler executes appropriate constructor. Table describes object declaration and appropriate constructor to it. Consider the following example:


Table: Overloaded Constructors

Constructor Declaration

Object Declaration

(a) num (int m, float j, char k);

(d) num x (4,5.5,‘A’);

(b) num (int m, float j);

(e) num y (1,2.2);

(c) num();

(f) num z;

In the above example, the statements (a), (b), and (c) are constructor declarations and (d), (e), and (f) are the object declarations. The compiler decides which constructor to be called depending on the number of arguments present with the object.

When object x is created, the constructor with three arguments is called because the declaration of an object is followed by three arguments. For object y, constructor with two arguments is called and lastly the object z, which is without any argument, is candidate for constructor without argument.

9.7 Write a program with multiple constructors for the single class.

Explanation: In the above program, three constructors are declared. The first constructor is with three arguments, second with two, and third without any argument. While creating objects, arguments are passed. Depending on number of arguments, compiler decides on the constructor to be called. In this program, x, y, and z are three objects created. The x object passes three arguments, the y object passes two arguments, and the z object passes no arguments. The function show() is used to display the contents of the class members.


9.8 Write a program to overload constructor and display date and time.

Explanation: The program has two constructors. The first constructor has six parameters. Six arguments are passed through the object to the first constructor.

The second constructor takes the date and time details entered through keyboard.

Test Your Skills Now!
Take a Quiz now
Reviewer Name