M
mead
The code is from a Meyers' book...
class BankAccount { ... }; // as above
// new class representing accounts that bear interest
class InterestBearingAccount: public BankAccount {
public:
virtual void creditInterest() = 0;
...
};
class SavingsAccount: public InterestBearingAccount {
... // as above
};
class CheckingAccount: public InterestBearingAccount {
... // as above
};
// better, but still not perfect
for (list<BankAccount*>::iterator p = allAccounts.begin();
p != allAccounts.end();
++p) {
static_cast<InterestBearingAccount*>(*p)->creditInterest();
}
Why did he use downcasting here to convert BankAccount* to
InterestBearingAccount*? Seems to this isn't necessary since
creditInterest() is a virtual function and creditInterest() in
InterestBearingAccount will be virtual and also in SavingsAccount and
CheckingAccount. So, (*p)->creditInterest(); will invoke creditInterest() in
SavingAccount or CheckingAccount as what virtual function supposes to work
like. Do I miss something? Thanks!
class BankAccount { ... }; // as above
// new class representing accounts that bear interest
class InterestBearingAccount: public BankAccount {
public:
virtual void creditInterest() = 0;
...
};
class SavingsAccount: public InterestBearingAccount {
... // as above
};
class CheckingAccount: public InterestBearingAccount {
... // as above
};
// better, but still not perfect
for (list<BankAccount*>::iterator p = allAccounts.begin();
p != allAccounts.end();
++p) {
static_cast<InterestBearingAccount*>(*p)->creditInterest();
}
Why did he use downcasting here to convert BankAccount* to
InterestBearingAccount*? Seems to this isn't necessary since
creditInterest() is a virtual function and creditInterest() in
InterestBearingAccount will be virtual and also in SavingsAccount and
CheckingAccount. So, (*p)->creditInterest(); will invoke creditInterest() in
SavingAccount or CheckingAccount as what virtual function supposes to work
like. Do I miss something? Thanks!