You are on page 1of 13

March 28, 2016 Lab 08: Inheritance

Student Name: __________________________Roll No: ______________ Section: ______________

LAB 08: INHERITANCE

Lab Objectives:
 Reasons for Inheritance
 Base and Derived Classes
 Derived Class Constructors
 Access Control
 Overridden Functions

1. REASONS FOR INHERITANCE


Inheritance is the process of creating new classes, called derived classes, from existing or base classes. The
derived class inherits all the capabilities of the base class but can add embellishments and refinements of
its own. The base class is unchanged by this process. Inheritance is illustrated in figure 01:

Inheritance is an essential part of OOP because:

 It permits code reusability. Once a base class is written and debugged, it need not be touched again,
but, using inheritance, can nevertheless be adapted to work in different situations.
 Reusing existing code saves time and money and increases a program’s reliability.

Page 1 of 10
March 28, 2016 Lab 08: Inheritance
Student Name: __________________________Roll No: ______________ Section: ______________

 Inheritance can also help in the original conceptualization of a programming problem, and in the overall
design of the program.
 An important result of reusability is the ease of distributing class libraries. A programmer can use a
class created by another person or company, and, without modifying it, derive other classes from it that
are suited to particular situations.

We’ll examine these features of inheritance in more detail after we’ve seen some specific instances of
inheritance at work.

2. BASE AND DERIVED CLASSES


Consider the following class TwoDShape, its objects can show the Dimensions( width and height) of a
shape.

If we need to display the Dimensions of a specific shape, let’s say a triangle, moreover we need to
calculate the area and display the style (isosceles triangle, right angled triangle etc.) of the triangle as
well. To do this we can add the required code in the class TwoDShape but this will be a very specific
approach and can result into a lengthy coded class TwoDShape if need to do the same for shapes other
than a triangle.
A generalized solution to this would be to apply inheritance i.e. we can create a class Triangle, derived
from class TwoDShape (now the base class), as shown in Example 01.

Page 2 of 10
March 28, 2016 Lab 08: Inheritance
Student Name: __________________________Roll No: ______________ Section: ______________

2.1.SPECIFYING THE DERIVED CLASS


Example 01:

In example 01, following the class TwoDShape in the listing is the specification for a new class, Triangle.
The first line of Triangle specifies that it is derived from TwoDShape:

Page 3 of 10
March 28, 2016 Lab 08: Inheritance
Student Name: __________________________Roll No: ______________ Section: ______________

class Triangle : public TwoDShape


Here we use a single colon (not the double colon used for the scope resolution operator), followed by the
keyword public and the name of the base class TwoDShape. This sets up the relationship between the
classes. This line says Triangle is derived from the base class TwoDShape.
REMEMBER: EVEN IF OTHER CLASSES HAVE BEEN DERIVED FROM IT, THE BASE
CLASS REMAINS UNCHANGED.

2.2. INHERITANCE AND ACCESSIBILITY


An important topic in inheritance is knowing when a member function in the base class can be used by
objects of the derived class. This is called accessibility. Let’s see how the compiler handles the accessibility
issue in the Example 01.
2.2.1. SUBSTITUTING BASE CLASS MEMBER FUNCTIONS
The object t1 of the class Triangle also uses the ShowDim() function from the class TwoDShape. The
compiler, not finding the function in the class of which t1 is a member, uses member function from the base
class.
This flexibility on the part of the compiler—using one function because another isn’t available—appears
regularly in inheritance situations.

2.2.2. SUBSTITUTING BASE CLASS CONSTRUCTORS


Similarly Constructors from the base class can also be used by the objects of the derived classes.
This practice is illustrated in Example 02:
Example 02-a:

Page 4 of 10
March 28, 2016 Lab 08: Inheritance
Student Name: __________________________Roll No: ______________ Section: ______________

Example 02-b:

In the main() part of Example 02 we create an object of class Triangle:


Triangle t1;
This causes t1 to be created as an object of class Triangle and initialized to 0. It turns out that, at least under
certain circumstances, if you don’t specify a constructor, the derived class will use an appropriate
constructor from the base class. In Example 02 there’s no constructor in Triangle, so the compiler uses
the no-argument constructor from TwoDShape.
REMEMBER: IN EXAMPLE 01, THE OBJECTS WERE USING THE DEFAULT
CONSTRUCTOR CREATED AUTOMATICALLY BY C++.

3. DERIVED CLASS CONSTRUCTORS


There’s a potential glitch in the Example 02 program. What happens if we want to initialize a Triangle
object to a value? Can we declare a parameterized constructor in TwoDShape and use it? The answer is
no. As we saw in Example 02, the compiler will substitute a no-argument constructor from the base
class, but it draws the line at more complex constructors. To make such a definition work we must
write a new set of constructors for the derived class. This is shown in Example 03:

Page 5 of 10
March 28, 2016 Lab 08: Inheritance
Student Name: __________________________Roll No: ______________ Section: ______________

Example 03:

This program uses a new constructor in the class Triangle. Here is the parameterized constructor:
Triangle (double a, double b): TwoDShape(a,b) {}

This constructor has an unfamiliar feature: the function name following the colon. This construction causes
the Triangle (double a, double b) constructor to call the TwoDShape(a,b)constructor in the base class. In
main(), when we say

Page 6 of 10
March 28, 2016 Lab 08: Inheritance
Student Name: __________________________Roll No: ______________ Section: ______________

Triangle t1(4.0. 4.0);


the compiler will create an object of type Triangle and then call the Triangle constructor to initialize it.
This constructor will in turn call the TwoDShape constructor, which carries out the work. The Triangle ()
constructor could add additional statements of its own.

4. THE PROTECTED ACCESS SPECIFIER


Notice in example 03, the access type of the member data of the class TwoDShape is now protected.
Previously the access type was kept public as the data members had to be initialized from main, but now
the parameterized constructor does that job.
Let’s first review what we know about the access specifiers private and public:

 Class members (which can be data or functions) can always be accessed by functions within their
own class, whether the members are private or public.
 But objects of a class defined outside the class can access class members only if the members are
public

This is all we need to know if we don’t use inheritance. With inheritance, however, there is a whole raft of
additional possibilities. The question that concerns us at the moment is, can member functions of the derived
class access members of the base class? In other words, can ShowArea() in Triangle access width and
height in TwoDShape. The answer is that member functions can access members of the base class if
the members are public, or if they are protected. They can’t access private members.

We don’t want to make member data public, since that would allow it to be accessed by any function
anywhere in the program and eliminate the advantages of data hiding. A protected member, on the other
hand, can be accessed by member functions in its own class or in any class derived from its own class.
It can’t be accessed from functions outside these classes, such as main(). This is just what we want.

In example 03 what will happen if we make the member data (width and height) private?
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
Access Specifier Accessible from Own Accessible from Accessible from
Class Derived Class Objects Outside Class
Public Yes Yes Yes
Protected Yes Yes No
Private Yes No No
Table 1. Inheritance and Accessibility

Page 7 of 10
March 28, 2016 Lab 08: Inheritance
Student Name: __________________________Roll No: ______________ Section: ______________

5. OVERRIDING MEMBER FUNCTIONS

You can use member functions in a derived class that override, that is, have the same name as those in the
base class. You might want to do this so that calls in your program work the same way for objects of both
base and derived classes

Example 04:

Who() in Base
Who() in Derived

5.1.WHICH FUNCTION IS USED?

How does the compiler know which of the two Who() functions to use? Here’s the rule:

 When the same function exists in both the base class and the derived class, the function in the
derived class will be executed. (This is true of objects of the derived class.)

 Objects of the base class don’t know anything about the derived class and will always use the base
class functions.

OTHER TERMS: IN SOME LANGUAGES THE BASE CLASS IS CALLED THE SUPERCLASS
AND THE DERIVED CLASS IS CALLED THE SUBCLASS. SOME WRITERS ALSO REFER TO
THE BASE CLASS AS THE PARENT AND THE DERIVED CLASS AS THE CHILD.

Page 8 of 10
March 28, 2016 Lab 08: Inheritance
Student Name: __________________________Roll No: ______________ Section: ______________

6. ASSIGNMENTS
Lab Assignment 01: Run example 01, attach the output and specify the base and derived classes.

Lab Assignment 02: Run example 02 and specify how the objects of Triangle class are initialized to 0?
Lab Assignment 03: Run example 03 and specify, what, is the function of the following line of code:
Triangle (double a, double b): TwoDShape(a,b)

Lab Assignment 04: Consider the following class Vehicle:

Derive a class called Car from Vehicle with:


 Member data model and color
 Member Functions to get and display data
 Also add Constructors to initialize objects.
Consider a sample run:

Lab Assignment 05-a: Draw the Class diagram of example 04.

Lab Assignment 05-b: Map the following class diagram into a C++ program:

Page 9 of 10
March 28, 2016 Lab 08: Inheritance
Student Name: __________________________Roll No: ______________ Section: ______________

Author
#name:string
#email:string
#gender:char
+Author(name:string, email:string,
gender:char)
+Display() : stirng, string, char

Book
-title: string;
-price: float
-ISBN: string
-publisher: string
+Book(name:string, email:string,
gender:char): Author
+GetData(): string, float string,
string
+ShowData() : stirng, float string,
string

Home Assignment 01: For your chosen semester project:


 List down the classes (you think should be involved)
 Create a class diagram of these classes, specify generalization (inheritance)

Home Assignment 02:

1. Inheritance is a way to
a. make general classes into more specific classes. b. pass arguments to objects of classes.
c. add features to existing classes without rewriting them. d. improve data hiding and encapsulation.
2. A “child” class is said to be _________ from a base class.
3. Advantages of inheritance include
a. providing class growth through natural selection. b. facilitating class libraries.
c. avoiding the rewriting of code. d. providing a useful conceptual framework.
4. Write the first line of the specifier for a class Bosworth that is publicly derived from a class Alphonso.
_____________________________________________________________________________________
5. To be accessed from a member function of the derived class, data or functions in the base class must be
public or _________.

Page 10 of 10
UML (UNIFIED MODELING LANGUAGE)

UML is different from the other common programming languages like C++, Java, COBOL etc. UML is a
pictorial language used to make software blue prints.

So UML can be described as a general purpose visual modeling language to visualize, specify, construct
and document software system. Although UML is generally used to model software systems but it is not
limited within this boundary. There are two basic types of UML diagrams.

STRUCTURALDIAGRAMS:
The structural diagrams represent the static aspect of the system. These static aspects represent those parts
of a diagram which forms the main structure and therefore stable.

These static parts are represents by classes, interfaces, objects, components and nodes. The four structural
diagrams are:

 Class diagram
 Object diagram
 Component diagram
 Deployment diagram

BEHAVIORAL DIAGRAMS:
Any system can have two aspects, static and dynamic. So a model is considered as complete when both
the aspects are covered fully.

Behavioral diagrams basically capture the dynamic aspect of a system. Dynamic aspect can be further
described as the changing/moving parts of a system.

UML has the following five types of behavioral diagrams:

 Use case diagram


 Sequence diagram
 Collaboration diagram
 Statechart diagram
 Activity diagram

Page 1 of 3
CLASS DIAGRAM:
Class diagrams are the most common diagrams used in UML. Class diagram consists of classes, interfaces,
associations and collaboration.

Class diagrams basically represent the object oriented view of a system which is static in nature.

Active class is used in a class diagram to represent the concurrency of the system.

Class diagram represents the object orientation of a system. So it is generally used for development
purpose. This is the most widely used diagram at the time of system construction.

HOWTODRAW CLASSDIAGRAM?
Class diagram is basically a graphical representation of the static view of the system and represents different
aspects of the application. So a collection of class diagrams represent the whole system.

The following points should be remembered while drawing a class diagram:

 The name of the class diagram should be meaningful to describe the aspect of the system.

 Each element and their relationships should be identified in advance.

 Responsibility (attributes and methods) of each class should be clearly identified.

 For each class minimum number of properties should be specified. Because unnecessary
properties will make the diagram complicated.

 Use notes when ever required to describe some aspect of the diagram. Because at the end of the
drawing it should be understandable to the developer/coder.

 Finally, before making the final version, the diagram should be drawn on plain paper and rework
as many times as possible to make it correct.

The following class diagram has been drawn considering all the points mentioned above:

Page 2 of 3
VISIBILITY
To specify the visibility of a class member (i.e. any attribute or function), these notations must be placed
before the member's name
- Indicates private
+ Indicates public
# Indicates protected

Page 3 of 3

You might also like