


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Solutions to exercise sheet 2 for the object-oriented programming in c++ module (in3013/inm173). It covers the account class, including constructor definitions, member function types (pure and procedural), and the bank class with a collection of accounts. The importance of constructor definitions and the use of const in method declarations.
Typology: Exercises
1 / 4
This page cannot be seen from the preview
Don't miss anything!



class Account { string name; double balance;
public: Account(string n) : name(n), balance(0) {} Account(string n, double initial_balance) : name(n), balance(initial_balance) {}
string get_name() const { return name; } double get_balance() const { return balance; }
void deposit(double amount) { balance += amount; }
void withdraw(double amount) { balance -= amount; } };
Note we have two kinds of member functions (methods) here:
Separating the methods this way makes the class easier to understand, but many classes have methods that both change the state and return something.
class Account { string name; double balance;
public: Account(string n); Account(string n, double initial_balance);
string get_name() const; double get_balance() const;
void deposit(double amount); void withdraw(double amount); };
Now the constructors will be defined outside the class, and so must be qualified with the class name:
Account::Account(string n) : name(n), balance(0) {} Account::Account(string n, double initial_balance) : name(n), balance(initial_balance) {}
Similarly the methods must be qualified when they are defined in this way:
string Account::get_name() const { return name; } double Account::get_balance() const { return balance; }
void Account::deposit(double amount) { balance += amount; }
void Account::withdraw(double amount) { balance -= amount; }
Note that the fields of the class are still accessible inside the constructors and meth- ods, just as if they had been defined inside the class.
account[i].deposit(amount); }
void withdraw(string name, double amount) { for (int i = 0; i < account.size(); i++) if (account[i].get_name() == name) account[i].withdraw(amount); }
These implementations are flawed, because they keep going after finding a matching name. They also terminate successfully if the name was not found, which would be inappropriate in a real bank. We could also have used references as in the previous part, but this time the references would not be const, as we’re modifying the objects they refer to.
void add_interest(double rate) { for (int i = 0; i < account.size(); i++) account[i].deposit( account[i].get_balance() * rate / 100); }