Lab2 Solutions
Lab2 Solutions
Programming in C++
Solutions to Exercise Sheet 2
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) {}
• pure functions, like get name and get balance, that return data and do not
change the object, as indicated by const.
• procedures, like deposit and withdraw, whose purpose is to change the object,
but do not return anything, as indicated by void.
Separating the methods this way makes the class easier to understand, but many
classes have methods that both change the state and return something.
2. This is achieved by the above class, which supplies constructors, but not a default one.
The compiler will only generate a default constructor for a class if no constructors
are supplied by the programmer.
1
3. Here is the class with all the active code removed:
class Account {
string name;
double balance;
public:
Account(string n);
Account(string n, double initial_balance);
Now the constructors will be defined outside the class, and so must be qualified with
the class name:
Similarly the methods must be qualified when they are defined in this way:
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.
2
class Bank {
vector<Account> account;
public:
void add_account(const Account &acct) {
account.push_back(acct);
}
Note that the reference acct must also be declared const, indicating that the
Account object will not be changed, and required by the const in the procedure
declaration.
3
account[i].deposit(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.
6. Again we loop through the accounts in the vector, doing the same thing to each: