Constructors With Default Arguments
Similar to functions, it is also possible to declare constructors with default arguments. Consider the following example:
power(int 9,int 3);
|
In the above example, the default value for the first argument is nine and two for second.
power p1 (3);
|
In this statement, object p1 is created and 9 raise to 3 expression n is calculated. Here, one argument is absent hence default value 9 is taken, and its third power is calculated. Consider the following example on the above discussion:
9.10 Write a program to declare default arguments in a constructor. Obtain the power of the number.
Explanation: In the above program, the class power is declared. It has three integer member variables and one member function show(). The show() function is used to display the values of member data variables. The constructor of class power is declared with two default arguments. In the function main(), p1 and p2 are two objects of class power. The p1 object is created without argument. Hence, the constructor uses default arguments in pow() function. The p2 object is created with one argument. In this call of constructor, the second argument is taken as default. Both the results are shown in output.