Page 134 - DCAP404 _Object Oriented Programming
P. 134
Unit 6: Constructors and Destructors
6.4 Parameterized Constructors Notes
If it is necessary to initialize the various data elements of different objects with different values
when they are created. C++ permits us to achieve this objective by passing arguments to the
constructor function when the objects are created. The constructors that can take arguments are
called ‘Parameterized constructors.’ The definition and declaration are as follows:
class dist
{
int m, cm;
public:
dist(int x, int y);
};
dist::dist(int x, int y)
{
m = x; n = y ;
}
main()
{
dist d(4,2);
d. show ();
}
Task C++ permits us to achieve this objects but passing argument to the constructor
function when the object are created. Discuss with a proper example.
6.5 Constructors with Default Arguments
This method is used to initialize object with user defined parameters at the time of creation.
Consider the following Program that calculates simple interest. It declares a class interest
representing principal, rate and year. The constructor function initializes the objects with principal
and number of years. If rate of interest is not passed as an argument to it the Simple Interest is
calculated taking the default value of rate of interest
#include <iostream.h>
#include <conio.h>
class interest
{ int principal, rate, year;
float amount;
public
LOVELY PROFESSIONAL UNIVERSITY 127