I’m trying to redefine two member functions from their parent’s definition.
I don’t know if I have it right or not, but something in my code has errors attached and I can’t find out what.
some of the header:
class Account
{
public:
Account(double);
void creditBalance(double);
void debitBalance(double);
double getBalance() const;
protected:
double balance;
};
class CheckingAccount : public Account
{
public:
CheckingAccount(double, double);
void feeCreditBalance(double);
void feeDebitBalance(double);
private:
double fee = 10;
};
relevant cpp file part:
void Account::creditBalance(double plus)
{
if(plus > 0)
balance += plus;
else
cout << "Cannot credit negative.";
}
void Account::debitBalance(double minus)
{
if(minus <= balance)
balance -= minus;
else
cout << "Debit amount exceeded account balance.";
}
void CheckingAccount::feeCreditBalance(double plus)
{
if(plus > 0){
balance += plus;
balance -= fee;
}
else
cout << "Cannot credit negative.";
}
void CheckingAccount::feeDebitBalance(double minus)
{
if(minus <= balance){
balance -= minus;
balance -= fee;
}
else
cout << "Debit amount exceeded account balance.";
}
UPDATE:
I added this:
class Account
{
public:
Account(double);
virtual void creditBalance(double);
virtual void debitBalance(double);
double getBalance() const;
protected:
double balance;
};
Now I get error: virtual outside class declaration
I could use an example of how to properly initialize fee correctly.
EDIT 2:
I have tried changing the constructor line to this:
CheckingAccount::CheckingAccount(double initBal, double phi) : Account(initBal), fee(phi)
{
if(initBal < 0)
initBal = 0;
balance = initBal;
cerr << "Initial balance was invalid.";
if(phi < 0)
phi = 0;
fee = phi;
}
not working, I’m going to work around with changing syntax on the fee(phi) part. I don’t know if anyone will respond to this.
If the intention is that for instances of CheckingAccount accounts the versions which use a fee is called, then you want to use virtual methods.
A virtual method is a method decalared (at least in the base class) as “virtual”, and has the same name and signiture in any derived classes. When a virtual method is called, it will call the “most derived” version for the instance.
To do this just declare “void creditBalance(double);” and “void debitBalance(double);” virtual (ie “virtual void creditBalance(double);” and “virtual void debitBalance(double);”. Then in CheckingAccount rename “feeCreditBalance” and “feeDebitBalance” to “creditBalance” and “debitBalance”.
EDIT: Simple example.
Header
Cpp
You can then derive from Derive again (class DerivedAgain : public Derived) and also overload the functions again.
You can also derive multiple subclasses from Base, which can each have their own overrides for the virtual methods, just like I did for the Derived class.
EDIT2: Added variables to example and how to use initialiser list to initialise the base class and member variables.