Week 1 - M5 : Inheritance
Learning Objectives
At the end of this module, you will be able to- Understand the implementation of inheritance in C++
- Override the base class members
- Access overridden base class members using the scope resolution operator
- Understand the concept of base class initialization
Introduction
Inheritance
The philosophy behind inheritance is to portray things as they exist in the real world. As inheritance is found in real world, it is important feature of OO programming. Inheritance has many advantages, the most important of them being the resuability of code. Once a class is defined and debugged, it can be used to create new subclasses. The reuse of existing class saves time and effort.The Class from which another class is derived is called the base class. The class which inherits the properties of the base class is called the derived class. Each instance of the derived class includes all the members of the base class. Since the derived class inherits all properties of the base class, the derived class has a larger set of properties than its base class. However, the derived class may override some or all the properties of the base class.
Any class can be a base class. More than one class can be derived from a single base class, and a derived class can be a base class to another.
if class d1 is inherited from class b1, then the syntax for declaring class derived is
class d1::public b1
An object defined outside the class can access only the public members of the class. Therefore, private members of a class cannot be directly accessed from outside the class. This holds true even for a derived class. Even though the derived class inherits all the members data and functions from the base class, private members of the base class are not directly accessible from the derived class. The idea behind this is never to compromise on encapsulation implemented through data hiding.
The protected members of a class can be accessed by its members functions, or within any class derived from it. Protected members behave like public members with respect to the derived class and like private members with respect to the rest of the program.
Overriding Base Class Members
A base class members can be overridden by defining a derived class member with the same name as that of the base class member.If the function exists in both the derived class and the base class then.
- If the function is invoked from an Object of the derived class, then the function in the derived class is executed.
- If the function is invoked from an Object of the base class, then the base class member function is invoked.
Inheritance Example in Real World
In a Banking System, Manager, Officers, Clerk have some common and as well as special behavior (specific tasks/actions). The commonality is that they are all employees of the Bank. A generalized class “Employee_GeneralizedClass” could be used to represent the commonality among Object classes.The generalization is often referred to as inheritance, and the generalized class as parent class. inheritance is a means of specifying hierarchical relationships between object classes.
Points to Remember
- The class from which a subclass is derived is referred to as the base class'.
- Base class constructors and destructors are not inherited by the derived class.
- Derived class constructors must explicitly call the base class constructors with appropriate parameters.
- Destructors are invoked in the reverse order.
Resources
Walk Through Video (here)Inheritance:
- http://www.cplusplus.com/doc/tutorial/inheritance.html
- http://www.csse.monash.edu.au/~jonmc/CSE2305/Topics/05.09.Inheritance/html/text.html#inheritance_in_c
Steps to attack the problem sets
- Step 1: Read the Introduction
- Step 2: Go through the Videos given in the Resources.
- Step 3: Go through the given PPT on Inheritance and try sample problems given in the PPT.(you can copy paste the programs from the PPT)
- Step 4: Go through the additional resources give for further clarification.
- Step 5: Attack the problem sets in the given order(Problem Set A and then Problem Set B).
- Step 6: If you are not clear with the problem sets then contact your respective mentor for clarification.
Problem Sets
Problem Set A
1. Draw an inheritance hierarchy for classes Quadrilateral, TRapezoid, Parallelogram, Rectangle and Square. Use Quadrilateral as the base class of the hierarchy. Make the hierarchy as deep as possible.The diagrams should include the state and behavior for each class.
Example Image for Inheritance is:
Name the document as : PA1_Quadrilateral.doc2. Draw an inheritance hierarchy for classes Shapes. Circle, Square, Triangle and Quadrilateral(described in previous task). Use the Shapes as the base class for the hierarchy. Make the hierarchy as deep as possible.
The diagrams should include the state and behavior for each class. Refer to the image given in PA1.
Refer: To the PPT given in the resources for inheritance.
Name the document as : PA2_Shapes.doc
Problem Set B
1. (Account Inheritance Hierarchy) Create an inheritance hierarchy that a bank might use to represent customers' bank accounts. All customers at this bank can deposit (i.e., credit) money into their accounts and withdraw (i.e., debit) money from their accounts. More specific types of accounts also exist. Savings accounts, for instance, earn interest on the money they hold. Checking accounts, for instance, charge a fee per transaction (i.e., credit or debit). Current accounts, on other hand, has overdraft(Negative balance) facility to withdraw the money.Create an inheritance hierarchy containing base class Account and derived classes SavingsAccount, CheckingAccount and CurrentAccount that inherit from class Account. Base class Account should include one data member of type double to represent the account balance. The class should provide a constructor that receives an initial balance and uses it to initialize the data member. The constructor should validate the initial balance to ensure that it is greater than or equal to 0.0. If not, the balance should be set to 0.0 and the constructor should display an error message, indicating that the initial balance was invalid. The class should provide three member functions. Member function credit should add an amount to the current balance. Member function debit should withdraw money from the Account and ensure that the debit amount does not exceed the Account's balance. If it does, the balance should be left unchanged and the function should print the message "Debit amount exceeded account balance." Member function getBalance should return the current balance.
Derived class SavingsAccount should inherit the functionality of an Account, but also include a data member of type double indicating the interest rate (percentage) assigned to the Account. SavingsAccount's constructor should receive the initial balance, as well as an initial value for the SavingsAccount's interest rate. SavingsAccount should provide a public member function calculateInterest that returns a double indicating the amount of interest earned by an account. Member function calculateInterest should determine this amount by multiplying the interest rate by the account balance. [Note: SavingsAccount should inherit member functions credit and debit as is without redefining them.]
Derived class CheckingAccount should inherit from base class Account and include an additional data member of type double that represents the fee charged per transaction. CheckingAccount's constructor should receive the initial balance, as well as a parameter indicating a fee amount. Class CheckingAccount should redefine member functions credit and debit so that they subtract the fee from the account balance whenever either transaction is performed successfully. CheckingAccount's versions of these functions should invoke the base-class Account version to perform the updates to an account balance. CheckingAccount's debit function should charge a fee only if money is actually withdrawn (i.e., the debit amount does not exceed the account balance). [Hint: Define Account's debit function so that it returns a bool indicating whether money was withdrawn. Then use the return value to determine whether a fee should be charged.]
Derived class CurrentAccount should inherit the functionality of an Account, but also include a data member of type double indicating the maximum overdraft limit (percentage) assigned to the Account. CurrentAccount's constructor should receive the initial balance, as well as an initial value for the CurrentAccount's maximum overdraft limit. CurrentAccount should redefine member function debit, so that the account holder can withdraw money upto a maximum of overdraft limit if the balance is below 0. [Note: An overdraft occurs when withdrawals from a bank account exceed the available balance which gives the account a negative balance]
After defining the classes in this hierarchy, write a Test program that creates objects of each class and tests their member functions. For Example: Add interest to the SavingsAccount object by first invoking its calculateInterest function, then passing the returned interest amount to the object's credit function.
You can write the class declarations in separate header files'as given in the example of the PPT anddefinitions in separate CPP file.
Use the Project in Dev C++ (File->New->Project) to compile and execute the programs
Comments
Post a Comment