Coupon Accepted Successfully!


Recursive Constructors

Similar to normal and member functions, constructors also support recursion. The following program explains this.


9.24 Write a program to invoke constructor recursively and calculate the triangular number of the entered number.

Explanation: In the above program, class tri_num is declared and with private integer f and member function sum(). The class also has zero-argument constructor and one-argument constructor.

In function main(), a is an object of tri_num class. When object a is declared, the zero-argument constructor is executed. The object a invokes the constructor explicitly and passes integer value to it. The passed value is received by the variable m of the constructor. The if statement checks the value of variable m and if it is zero, the triangular number is displayed and the program is terminated.

The sum() function is called by the constructor and the cumulative sum is calculated and stored in the member variable f. Followed by the call of function sum(), the constructor tri_num() is executed and the value of m is decreased by one. Thus, the recursion takes place and each time value of m decreases. When the value of m becomes zero, as mentioned above, the program terminates and we get the triangular number.


Tip: Recursion is not difficult, though somewhat confusing. If you are still confused about recursion concept, execute the program in a single step to know the flow of the program. First, try the recursion with normal function in C style and after perfect understanding try with member function and constructors, but do not drop it.

Test Your Skills Now!
Take a Quiz now
Reviewer Name