Consider the following code for
class BankAccount
{
protected:
int accNo;
int balance;
std::string custName;
std::string custAddress;
public:
BankAccount(int aNo, int bal, std::string name, std::string address);//:accNo(aNo), balance(bal), custName(name), custAddress(address);
BankAccount(const BankAccount&);
BankAccount();
~BankAccount();
BankAccount& operator=(const BankAccount&);
int getAccNumber() const {return accNo;};
virtual int getBalance() const {return balance;};
std::string getAccountHolderName()const {return custName;};
std::string getAccountHolderAddress()const {return custAddress;};
virtual std::string getAccountType()const{return "UNKNOWN";};
};
class CurrentAccount:public BankAccount
{
private:
int dailyTrancLimit;
public:
CurrentAccount(int aNo, int bal, std::string name, std::string address);
int getTransactionLimit()const {return dailyTrancLimit;};
void setTranscationLimit(int transLimit){dailyTrancLimit = transLimit;};
std::string getAccountType()const{return "CURRENT";};
};
class SavingAccount:public BankAccount
{
private:
int intrestRate;
int accumuatedIntrest;
public:
SavingAccount(int aNo, int bal, std::string name, std::string address);
int getBalance()const {return balance+accumuatedIntrest;};
void setIntrestEarned(int intrest){accumuatedIntrest=intrest;};
std::string getAccountType()const{return "SAVINGS";};
};
I want to call setIntrestEarned()
in SavingAccount class with base class pointer. I don't want to add setIntrestEarned()
as virtual
in base class BankAccount because it has no meaning in the other type of accounts like derived one CurrentAccount.
And if we keep adding various function in different derived class as virtual in base class then it will end up like a superset of functions of derived class.
What would be the best way to design these type of class hierarchy?
Base
class are definitely instances ofDerived
class (which you have to know if you want to reliably call a method of the derived class on them), then you can cast them to the derived class to call on that. – Zinkidynamic_cast<SavingAccount*>()
is your friend – Adrian Wstatic_cast<T*>(p)
if and only if you know for sure that the object pointed to byp
is of typeT
.dynamic_cast<T*>
will return anullptr
if the object pointed to is not of classT
. – Adrian W