Coupon Accepted Successfully!


Dynamic Initialization Using Constructors

After declaration of the class data member variables, they can be initialized at the time of program execution using pointers. Such initialization of data is called dynamic initialization. The benefit of dynamic initialization is that it allows different initialization modes using overloaded constructors. Pointer variables are used as argument for constructors. The following example explains dynamic initialization using overloaded constructor.

9.21 Write a program to initialize member variables using pointers and constructors.

Explanation: In the above program, the class city is declared with three-character arrays: city, state, and country. The class city also has four constructors: zero-argument constructor, one-argument constructor, two-argument constructor, and three-argument constructor. The display() member function is used to display the contents on the screen.

In function main(), c1, c2, c3, and c4 are declared and strings are passed. According to the number of arguments, respective constructor is executed. The function display() is called by all the four objects and information displayed is as shown in the output. While calling function display(), the line format “=====” is passed that is displayed before displaying the information. The display() function also contains if statements that check the length of the string and display the string only when the variable contains string. In case the data variable contains NULL, the string will not be displayed. The object c4 is initialized with NULL character. The use of c4 object is only to display a line at the end of a program.

Test Your Skills Now!
Take a Quiz now
Reviewer Name