Constructors With Arguments (Parameterized Constructor)
In the previous example, constructors initialize the member variables with given values. It is also possible to create constructor with arguments, and such constructors are called parameterized constructors. For such constructors, it is necessary to pass values to the constructor when an object is created. Consider the following example:
In the above example, the declaration and definition of a constructor contains three integer arguments. In the definition, the three arguments m, j, and k are assigned to member variables a, b, and c.
In a situation like this when class has a constructor with arguments, care is to be taken while creating objects. So far, we created the object using the following statement:
This statement will not work. We need to pass required arguments as per the definition of constructor. Hence, to create object, the statements must be as given below:
(a) class num x=num (4,5,7); // Explicit call
(b) class num y (9,5,7); // Implicit call
The statements (a) and (b) can be used to create objects, which not only create objects but also pass given values to the constructor. The method (a) is called explicit call and the method (b) implicit call.
9.6 Write a program to create a constructor with arguments and pass the arguments to the constructor.
Explanation: In the above program, x and y are objects of class num. When objects are created, three values are passed to the constructor. These values are assigned to the member variables. The function show() displays the contents of member variables.