Here are two things you need to remember when you work with constructors:
1) A constructor MUST have the same name as the class.
The constructor for class Loan is called Loan.
2) A constructor does not have a type, thus it CANNOT return a value.
In the Loan class, the set function can be replaced with the constructor as its job is to initialize the variable members of the class.
Here is the P62a.cpp program with constructors.
// P63.cpp - This program is a driver
written to demonstrate how the constructor function works.
class Loan // Loan is called structure tag
Loan(int ID, float amount, float rate, int term);
void set( );
float payment( );
void display( );
int ID; // assume an unique integer between 1111-9999
float amount; // $ amount of the loan
float rate; // annual interest rate
int term; // number of months, length of the loan
int main( )
Loan loan1(1234, 2300, 5.5, 48); // initialize to values given
Loan loan2; // use the default values
Loan loan4 = loan1;
cout << "Display loan1 \n";
cout << "Display loan2 \n";
cout << "Display loan4 \n";
loan3.set( ); // set the values
cout << "Display loan3 \n";
// Body intentionally kept empty so the default values are used.
// If you wish to set the default value of the members to specific
// values, here is the place to do it.
// For example, to make the default value of amount = 0
// you will use amount = 0;
// You could actually copy the body of set
function here too
Loan::Loan(int I, float am, float rt, int trm)
ID = I;
amount = am;
rate = rt;
term = trm;
void Loan::set( )
// Initialize the loan1 object
cout << "Enter the ID of this loan \n";
cin >> ID;
cout << "Enter the amount of
this loan \n";
cin >> amount;
cout << "Enter the annual interest
rate of this loan (in %) \n";
cin >> rate;
cout << "Enter the term (number
of months, length of the loan) \n";
cin >> term;
cout << ID << endl;
cout << amount << endl;
cout << rate << endl;
cout << term << endl;
Modify the above program or the ex63.cpp program to include constructors that help perform the same computation as requested in Exercise 6.3. Call your new program ex64.cpp.