0% found this document useful (0 votes)
20 views10 pages

Polymorph Is M

Uploaded by

benji20167
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views10 pages

Polymorph Is M

Uploaded by

benji20167
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Lab Manual for Object-Oriented Programming

(LAB-12)
Polymorphism in Object Oriented Programming

Department of Computer Science, Page 106


SST, UMT
Polymorphism in Object Oriented Programming

Table of Contents
1. Introduction 108

2. Activity Time Boxing 110

3. Objective of the Experiment 110

4. Concept Map 110

5. Homework before Lab 110


5.1 Problem Solution Modeling 110
5.2 Practices from home 111

6. Procedure & Tools 111


6.1 Tools 111
6.2 Setting-up Visual Studio 2008 111
6.3 Walk-through Task 111

7. Practice Tasks 113


7.1 Practice Task 1 113
7.2 Practice Task 2 113
7.3 Outcomes 114
7.4 Testing 114

8. Evaluation Task (Unseen) 114

9. Evaluation Criteria 114

10. Further Reading 114


10.1 Books 114
10.2 Slides 114

Department of Computer Science, Page 107


SST,UMT
Polymorphism in Object Oriented Programming

Lab 12: Polymorphism in Object Oriented


Programming
1. Introduction
In general, polymorphism means „various shapes‟ and within the context of an object-oriented programming (OOP)
language, it is the ability of an object to acquire various forms while referencing various instances of the different
classes in inheritance hierarchy. In OOP, a significant characteristic is the type compatibility of a derived class pointer
to its base class pointer. Taking advantage of this useful aspect, polymorphism establishes a new way of programming.

To realize polymorphism in C++, you need


 A virtual function and
 A pointer of base class type

A member function of a base class can be made a virtual function if it is probable to redefine (override) this function
in the derived class. The significance of making a function virtual becomes evident when you want to invoke function
of derived class from a pointer of base class referencing derived class‟ object. Following code provides an example
of polymorphism mechanism in C++.
USER
2013-08-23 15:58:16
class Base
--------------------------------------------
{
class's
public:
virtual void Func()
{
cout<<”Base Class Function”;
}
};

class Derived: public Base


{
public:
void Func()
{
cout<<”Derived Class Function”;
}
};
void main()
{
Base *bPtr;
Derived Dev;
bPtr = Dev;
bPtr->Func();
}

Upon calling Func() with bPtr, Derived class Func() will be invoked and output would be “Base Class Function”.
In the absence of virtual keyword, Func() of base would be called each time. Hence, it can be concluded that virtual
USER
keyword allow a pointer of base class to call appropriate function of any of its derived class2013-08-23
to whom it15:59:34
is referencing.
In this way, each time a different function will be invoked with the same function call. With polymorphism, compiler
--------------------------------------------
does not know which function to call at compile and thus appropriate function call is deferred to runtime. At runtime,
funt()
the type of object that a base class pointer is pointing is recognized to call proper function. This is known as dynamic
or late binding.

Virtual keyword can also be used with destructors and classes. However, virtual keyword possess different meanings
when used with destructor and classes as explained below.

Department of Computer Science, Page 108


SST,UMT
Polymorphism in Object Oriented Programming

Virtual Destructors:
In practice, it is always recommended to make the base class destructor as virtual. In the absence of virtual keyword
with base class destructor, upon deletion of any derived class‟ object only destructor of base class would be called.

Virtual Base Classes:


Virtual base classes can be used to avoid diamond problem of multiple inheritance that is explained as under.

class Base
{
protected:
void Func()
{ cout<<”A Base Class Function”; }
};
class Derived1: public Base{ };
class Derived2: public Base{ };
class Derived3: public Derived1, public Derived2
{ };

In the code above, both (Derived1 and Derived2) classes contain a copy of Func(), which is inherited from class Base.
Upon the invocation of Func() with an object of Derived3 class, compiler would be unable to decide which copy to
use.

To overcome this situation, it is required to use virtual keyword with base class inheritance. Hence, the above code
would be implemented as

class Base
{
protected:
void Func()
{ cout<<”A Base Class Function”; }
};
class Derived1: virtual public Base{ };
class Derived2: virtual public Base{ };
class Derived3: public Derived1, public Derived2
{ };

Pure Virtual Function and Abstract Class:


You may have observed that with any class hierarchy in OOP, derived class(es) become are more specific version of
base class(es) which are more general or abstract. It is sometime good in practice to make the base class as abstract
class that contains only the most common features of all of its derived classes. In C++, you can make base class an
abstract class by declaring a pure virtual function in it. The syntax is given as under:

class Base
{
protected:
virtual void Func() = 0;
};

Instantiation of an abstract class is not possible and you should override pure virtual function in derived class(es).

Relevant Lecture Readings:


 Lectures: 23, 24, 25, 26
 Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore.
o Pages: 503- 520
Department of Computer Science, Page 109
SST,UMT
Polymorphism in Object Oriented Programming

2. Activity Time Boxing


Table 1: Activity Time Boxing

Task No. Activity Name Activity time Total Time


6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walk-through Tasks 30 mins 30 mins
7 Practice tasks 90 mins for two task 90 mins
9 Evaluation Task 55 min for all assigned task 55 mins
Total Time 180 mins

3. Objective of the Experiment


After completing this lab, the student should be able to:
 Distinguish between static binding and dynamic binding
 Understand polymorphism and dynamic binding while using virtual functions
 Declare abstract classes with pure virtual function

4. Concept Map
Following encapsulation and inheritance, polymorphism is the third important capability of OOP paradigm. The
fundamental inspiration behind polymorphism is that of dynamic binding. In this way, at compile time, compiler
knows nothing about which function to call. On the contrary, decision is made at runtime. Polymorphism helps
programmer to make program in general rather than specific. In simple words, it provides a single interface with
different implementations. Moreover, polymorphism facilitates program extensibility while permitting new derived
classes and functions to be added to an inheritance hierarchy without modifying application programs that already
utilize various interfaces of that inheritance hierarchy. However, for beginners, it is difficult to grasp and implement
the concept of polymorphism, dynamic binding, and abstract classes.

5. Homework before Lab

5.1 Problem Solution Modeling

Draw UML class diagrams of the following task. You are required to bring this design with you and submit to
your lab instructor.

5.1.1 Problem description:

Design a class named Student that includes


 A data member named rollNo
 A parameterized constructor to initialize rollNo
 A getter function to get the value of rollNo

Derive a class named Exam inherited from Student class and contains
USER
 Two additional data members i.e. course1 and course2 2013-08-23 16:36:54
 A parameterized constructor to initialize its own data fields along with the inherited data field
--------------------------------------------
 Two getter functions that return the value of course1 and course2, respectively Exam and Student can be associated but
E
mhad no real world inheritance relation
a
x
with Student.
Derive a class named Result inherited from class Exam and has

 A data field named totalMarks


 A member function named Display to show marks of course1, course2, and totalMarks (marks of course1
+ marks of course2)

Department of Computer Science, Page 110


SST,UMT
Polymorphism in Object Oriented Programming

Draw UML diagram for each class and show inheritance relationship between these classes.

5.2 Practices from home

5.3.1 Task-1

Consider four classes i.e. Person, Staff, Professor, and Researcher with the following inheritance hierarchy:

Class Researcher is derived from both Staff and Professor classes that are ultimately derived from class Person.

Class Person has two attributes i.e. name and age and one member function display() to show its attribute values.
Class Staff has two attributes i.e. staffID and department.
Class Professor has two attributes i.e. courseID and courseName.
USER
Class Researcher has an additional attribute named labID and experimentNo. 2013-08-23 16:45:57
USER
--------------------------------------------
2013-08-23 16:46:24
Draw UML diagram for each class and show inheritance relationship between these classes.
--------------------------------------------
no logical abstraction of both attributes
toProfesor. as above
same
5.3.2 Task-2

Illustrate the implementation of classes that have been specified in Task-1 using C++ compiler in a way that avoid
USER
diamond problem of multiple inheritance. 2013-08-23 16:51:48
--------------------------------------------
6. Procedure & Tools A task should be given on Diamond Shaped
problemin multiple inheritance considering
6.1 Tools thefigure 1 of lab 10 at page 92. as it is
related to that case.
Visual Studio 2008.

6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]


Setup visual studio and make a project named “Polymorphism”

6.3 Walk-through Task [Expected time = 30 mins]

In this task, you are required to write a C++ code which would elaborate polymorphism concept. The following lines
show the output of a basic polymorphism concept:

6.3.1 Writing Code

In the source file, which is created in the project “Polymorphism” write following C++ code:

Department of Computer Science, Page 111


SST,UMT
Polymorphism in Object Oriented Programming

.
Figure 1: Polymorphism

Figure 2: Main function for Figure 1

Department of Computer Science, Page 112


SST,UMT
Polymorphism in Object Oriented Programming

6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.

6.3.3 Executing the Program


A sample output after running the program is shown below:

USER
2013-08-23 16:54:43
--------------------------------------------
not visible

Figure 3: Final Output

7. Practice Tasks

This section will provide more practice exercises which you need to finish during the lab. You need to finish the
tasks in the required time. When you finish them, put these tasks in the following folder:
\\dataserver\assignments$\OOP\Lab12

7.1 Practice Task 1 [Expected Time = 45 mins]


Consider an abstract class Computer having
 Two fields (i.e. companyName, price) and
 A single function named show()

A class named Desktop inherits Computer class and adds fields representing
 color, monitor size, and processor type and
 Override function named show() to display values of its all attributes

A class named Laptop inherits Computer class and adds fields representing
 color, size, weight, and processor type and
 Override function named show() to display values of its all attributes

Write a main() function that instantiates objects of derived classes to access respective show() function using
dynamic binding.

7.2 Practice Task 2 [Expected Time = 45 mins]


Create a class named Person, which contains
 A pure virtual function named print()
 Two data fields i.e. personName and age

A class named Patient inherits Person class, which contains


 Three data fields i.e. disease type and recommended medicine
 Overridden function print() to display all details relevant to a patient

A class named MedicarePatient inherited from class Patient, which holds


 A data field representing the name of the hospital
 A data filed representing the name of the ward
Department of Computer Science, Page 113
SST,UMT
Polymorphism in Object Oriented Programming

 A data field representing roomNo

Department of Computer Science, Page 114


SST,UMT
Exception Handling

 Overridden function print() to display all details relevant to a patient

In the main function, create instances of derived classes to access respective print() function using dynamic
binding.

7.3 Outcomes
After completing this lab, student will be able to implement the concepts of virtual functions, dynamic binding, pure
virtual function, and abstract classes.

7.4 Testing
 For Practice Task 1, it is required to check the assignment of derived class instances to base class pointer.
Moreover, (while considering the dynamic binding) test the invocation of respective show() function.

 For Practice Task 2, it is required to check the assignment of derived class instances to base class pointer.
Moreover, (while considering the dynamic binding) test the invocation of respective print() function.

Table 3: Practice Tasks Confirmation

Practice Tasks Confirmation


T1
T2

8. Evaluation Task (Unseen) [Expected Time = 55 mins for all tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned the
marks percentage which will be evaluated by the instructor in the lab whether the student has finished the
complete/partial task(s).

Table 4: Evaluation of the Lab

Sr. No. Task No Description Marks


1 6 Procedures and Tools 10
2 7.1 Practice tasks and Testing 55
3 8.1 Evaluation Tasks (Unseen) 20
4 Comments 5
5 Good Programming Practices 10
Total Marks 100

10. Further Reading

10.1 Books

a) Object-Oriented Programming Using C++; Joyce Farrell, Fourth Edition

10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\

Department of Computer Science, Page 115


SST,UMT

You might also like