Constructors allow the initialisation of the state of an object when it is created. Suppose we were to initialise the states of an object using the following format:
// Is this OK? class account{ int myAccountNumber = 242343; float myBalance = 0.00; public: //etc.. };
No this is not sufficient!:
Even if we were allowed to do this, we cannot leave every instance of this class with the same bank account number and balance.
We need a way to update the account number and initial balance when the object is being created.
A Constructor can be used for this task:
So using constructors with the Account
class:
1 2 // Basic Bank Account Example with Constructors 3 4 #include<iostream> 5 6 using namespace std; 7 8 class Account{ 9 10 int accountNumber; 11 float balance; 12 13 public: 14 15 Account(float, int);16 virtual void display(); 17 virtual void makeLodgement(float); 18 virtual void makeWithdrawal(float); 19 }; 20 21 Account::Account(float aBalance, int anAccNumber)
22 { 23 accountNumber = anAccNumber; 24 balance = aBalance; 25 } 26 27 void Account::display() 28 { 29 cout << "account number: " << accountNumber 30 << " has balance: " << balance << " Euro" << endl; 31 } 32 33 void Account::makeLodgement(float amount) 34 { 35 balance = balance + amount; 36 } 37 38 void Account::makeWithdrawal(float amount) 39 { 40 balance = balance - amount; 41 } 42 43 int main() 44 { 45 Account anAccount = Account(35.00, 1234); //OK
46 Account testAccount(0.0, 1235); //OK
47 //Account myAccount = Account(); //Wrong!
48 49 anAccount.display(); 50 testAccount.display(); 51 } 52
The source code for this is in
BasicAccount2.cpp
Instead of the notation used above to set the states of the object, we can also use a member initialisation list, that sets the states within the constructor definition. So, if we use member initialisation lists with the previous constructor, it would look like:
// the constructor code implementation Account::Account(float aBalance, int anAccountNumber) :accountNumber(anAccountNumber), balance (aBalance)
{ // anything else, place here! }
![]() | The : denotes the use of the Member Initialisation List. |
![]() | The |
This format may seem complex, but if the class contains an object that must be initialised in the constructor (i.e. IS A PART OF) then the member initialisation list must be used.
© 2006
Dr. Derek Molloy
(DCU).