We discussed abstract classes previously as in the section called “Abstract Classes” in the context of general Object-Oriented Programming. An abstract class in C++ is a class that can have state variables and member methods, however, it provides no implementation for at least one of those member methods, i.e. it is incomplete.
Some C++ compilers expect you to define at least one derived class for each abstract class.
Using the same banking example as before, the use of abstract classes can be demonstrated. Suppose
the Account
class is modified to add a new abstract method called
getAccountType()
that returns a string defining the type of account. We can
require that every child of the Account
class implements this method and we
can even use the method getAccountType()
in the Account
class in spite of the fact that the method has no implementation. So the Account
will look like the following:
1 2 3 #include<iostream> 4 #include<string>5 6 using namespace std; 7 8 class Account{ 9 10 protected: 11 12 int accountNumber; 13 float balance; 14 15 public: 16 17 Account(float aBalance, int anAccountNumber); 18 virtual string getAccountType() = 0;
19 virtual void display(); 20 virtual void makeLodgement(float); 21 virtual void makeWithdrawal(float); 22 }; 23 24 Account::Account(float aBalance, int anAccNumber) 25 { 26 accountNumber = anAccNumber; 27 balance = aBalance; 28 } 29 30 void Account::display(){ 31 cout << "Account type: " << getAccountType() << endl;
32 cout << "account number: " << accountNumber 33 << " has balance: " << balance << " Euro" << endl; 34 } 35 36 ... 37 38
The full source code for this example is in
AbstractCurrentAccount.cpp
1 2 3 class CurrentAccount: public Account 4 { 5 float overdraftLimit; 6 7 public: 8 9 CurrentAccount(float balance, int accountNumber, float limit); 10 virtual string getAccountType();11 virtual void setOverDraftLimit(float newLimit); 12 virtual void display(); 13 virtual void makeWithdrawal(float amount); 14 }; 15 16 CurrentAccount::CurrentAccount( float balance, int accountNumber, float limit): 17 Account(balance, accountNumber), overdraftLimit(limit) 18 {} 19 20 string CurrentAccount::getAccountType() 21 { return "Current Account"; }
22 23 void CurrentAccount::display() 24 { 25 Account::display();
26 cout << " And overdraft limit: " << overdraftLimit << endl; 27 } 28 29 ... 30 31 int main() 32 { 33 //Account a = Account(35.00,34234324); NOT ALLOWED 34 //Account *ptrA = &a; 35 36 CurrentAccount b = CurrentAccount(50.0, 12345, 200.0); 37 b.display();
38 } 39 40
The full source code for this example is listed in
AbstractCurrentAccount.cpp
© 2006
Dr. Derek Molloy
(DCU).