Applications With Constructors
The initialization of member variables of class is carried out using constructors. The constructor also allocates required memory to the object. An example of a constructor is as follows:
In the above example, class num has three member integer variables a, b, and c. The declaration of constructor can be done inside the class and definition outside the class. In definition, the member variables of a class num are initialized to zero.
In the function main(), x is an object of type class num. When an object is created, its member variables (private and public) are automatically initialized to the given value. The programmer need not write any statement to call the constructor. The compiler automatically calls the constructors. If programmer writes a statement for calling a constructor, a constructor is called again. In case there is no constructor in the program, the compiler calls a dummy constructor. The constructor without argument is known as default constructor.
9.3 Write a program to define a constructor and initialize the class data member variables with constants.
Explanation: In the above program, the class num is declared with four integers a, b, c, and x. The variables a, b, and c are private and x is a public variable. The class also has show() function and constructor prototype declaration. The function show() displays the contents of the member variables on the screen. The definition of a constructor is done outside the class. In the function main(), x is an object of class num. When an object is created, constructor is automatically invoked and member variables are initialized to given values as per the constructor definition. The values of variables x, a, b, and c are as per the output shown. The compiler calls the constructor for every object created. For each object the constructor is executed once; that is, the number of times the execution of constructor is equal to the number of objects created. The below-given program explains this point.
9.4 Write a program to show that for each object constructor is called separately.
Explanation: In the above program, x, y, and z are objects of class num. A is an array of objects. For each individual object constructor is called. The total number of objects declared is five; hence, the constructor is called five times.
9.5 Write a program to read values through the keyboard. Use constructor.
Explanation: The above program is same as the previous one. In this program, whenever an object is created, the constructor is called and it reads the integer values through the keyboard. Thus, the entered constants are assigned to member variables of the class. Here, the constructor is used like other functions.