Coupon Accepted Successfully!


More Programs

9.29 Write a program to pass arguments to constructor. Define conditional constructor.


Explanation: In the above program, struct num is declared. The structure is without any data member. The struct contains constructor and destructor. In function main(), x is an object. Before creating object x, an integer and a character are entered through the keyboard in variables u and o, respectively. The variables u and o are passed to the constructor. The switch case statement within the constructor selects appropriate operation depending upon the value of variable o.

9.30 Write a program to copy constructor. Change the values of an object by calling the constructor.

Explanation: In the above program, the class data is declared with three data member variables and one member function show(). The class data also contains destructor and overloaded constructors. For explanation of this program, please refer Program 5.7. In this program, the object z is created and no arguments are passed. In such a case, the constructor with no arguments is executed and the entire data members are initialized to NULL. The statement z = data (1,70,5.8) explicitly calls the constructor and the object z is initialized. The result of the program is as given above.


9.31 Write a program to call the constructor without using object.

Explanation: In the above program, class A has three member variable c, i, and f of char, int, and float type. The class A also one-member function out() and a constructor. The constructor invokes the out() function to output the contents on the screen. In function main(), no object is declared. The constructor is called directly.

9.32 Write a program to demonstrate the use of copy constructor.

Explanation: In the above program, d1, d2, d3, and d4 are objects of the class data. The statement d4 = d2 = d1 invokes the overloaded operator = and assignment is carried out. The statement data d3 = d1 executes the copy constructor. The operator = () returns an object of class data type and initializes it using three-parameter constructor. The above approach creates an extra copy of the object that occupies extra memory space. To overcome this problem, we can use copy constructor method in which no new object is created.

9.33 Write a program to invoke constructors of nested classes.

Explanation: In the above program, classes A, B, and C are declared. The class B is declared inside the class A. The class C is declared inside the class B. A and B are qualified classes for class C. The class A is qualified class for class B. Each class has a constructor that initializes and displays the contents of the object.

Test Your Skills Now!
Take a Quiz now
Reviewer Name