0% found this document useful (0 votes)
116 views

POLYMORPHISM - Unit 11

The document discusses the concept of polymorphism in programming. It defines polymorphism as the ability for different classes that inherit from a common parent class to respond differently to the same method or function. The key aspects of polymorphism covered include virtual functions, abstract base classes, pure virtual functions, and how polymorphism is implemented using a virtual function table.

Uploaded by

Syafiq Fauzi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views

POLYMORPHISM - Unit 11

The document discusses the concept of polymorphism in programming. It defines polymorphism as the ability for different classes that inherit from a common parent class to respond differently to the same method or function. The key aspects of polymorphism covered include virtual functions, abstract base classes, pure virtual functions, and how polymorphism is implemented using a virtual function table.

Uploaded by

Syafiq Fauzi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 21

Polymorphism

QF002/11/1

UNIT 11

POLYMORPHISM

OBJECTIVES

General Objective

To understand and apply principles of


polymorphism in programming.

Specific Objective :

At the end of the unit you should be able to : -

 Explain Polymorphism.  Apply Polymorphism In A Program.  Use Polymorphism In A Program  Write And Design A Simple Polymorphism Program.

Polymorphism

QF002/11/2

INPUT

11.0

Introduction

  

The word polymorphism is derived from Greek which mean many forms. Polymorph is an act of changing from one class to another related class .
Polymorphism occurs when a single function represents

different

tasks.

Operator

overloading

is

the

multiple

implementation of the actions of an operator where the particular implementation depends on the types of the operand.  
Polymorphism is potentially different objects in a class

hierarchy to respond differently to the same message. In programming C++, polymorphism is a situation which in the same name is used for more than one distinct function or method.

Polymorphism occurs when a single method name,is used up and down the hierarchy of object. It acts in an appropriate, possibly different, way for each object

Yes.. Sir

Polymorphism

QF002/11/3

11.1

Virtual Function

  

The C++ keyword virtual enables the object-oriented features of polymorphism.


Virtual function enables you to call a function depending on

the type of class object. An Example of statement declaration is shown in the figure below:
Class Ppoly { protected : virtual void func1() };

Figure11.1: An Example Of Statement Declaration

Virtual function enables you to call a function depending on the type of class object

What is Virtual Function ?

Polymorphism

QF002/11/4

An example of virtual function statement program is shown below:

Class Ppoly { public: virtual void func1() { cout << calling Ppoly :: func1()\n, } }; class PDerived : public Ppoly // derive from Ppoly { public: void func1() { Ppoly::func1(); // call the inherited member function

Virtual function

Nonvirtual functions

Figure11.2:An Example Of Virtual Function Statement


Virtual functions are supported by a virtual function table, which incurs runtime overhead, both in the size of the program and in the performance of the program. If you have very small classes that you don't expect to subclass, you may not want to make any of the functions virtual.

Why not make all functions virtual?

Polymorphism

QF002/11/5

11.2

Abstract Base Class

An abstract base class is when a base class designed merely as a generic blueprint for more specialized c lasses but is not meant to be used by itself.

An abstract base class can never have objects created from it, its purpose is to act only as the parent class for their child classes to build on.

Abstract base class is a C++ class that contains at least one


pure virtual function.

Base class is a terminal or base case in a recursive task that stops the recursion process.

note

Remember that you can use an abstract base class only as a base class for deriving other classes

Polymorphism

QF002/11/6

11.3 Shared Base Class

What happens if both Bird and Horse inherit from a common base class, such as Animal? Figure 11.3 below illustrates what this looks like. Two base class objects exist. When a function or data member is called in the shared base class, another

ambiguity exists.

Figure11.3:An Example Of Common Base Classes

Polymorphism

QF002/11/7

11.4 Pure Virtual Function

A pure virtual function is a virtual function declaration in a base class that is set equal to zero. The base class provides on implementation of a pure virtual function, leaving this task up to the classes derived from the base class.

The following is a class declaration for some new class Pba se which declares a pure virtual function Dmath() as shown below.
Class PBase { public : virtual void };

Dmath() = 0;

Figure11.4:An Example Of Statement That Declares A Pure Virtual Function  An example of abstract base class program is shown below.
Pure virtual function Pbase::Draw() makes Pbase an abstract base class
class Pbase { protected: virtual void draw ()=0; };

Attempts to initiate an abstract base class object which should cause the compiler to generate an error.

void main() { Pbase b; // Error ? can't instantiate abstract class }

Figure11.5:An Example of Statement Declares A Pure Virtual Function

Polymorphism

QF002/11/8

11.5

Implementing Pure Virtual Functions

 The pure virtual functions in an abstract base class is never implemented. This is because no objects of that type are ever created. There is no reason to provide the implementations, and the ADT works purely as the definition of an interface to objects which derive from it.  It is possible, however to provide an implementation to a
pure virtual function Objects derived from the ADT,

perhaps to provide common functionality to all the overridden functions, can then call the function.  Figure 11.6 below shows an example program to implement
pure virtual functions. The additional functionality is

simply an additional message printed, but one can imagine that the base class provides a shared drawing mechanism. Perhaps setting up a window that all derived classes will use.
//Implementing pure virtual functions #include <iostream.h> enum BOOL { FALSE, TRUE };

class Shape { public: Shape(){} ~Shape(){} virtual long GetArea() = 0;//error virtual long GetPerim()= 0; virtual void Draw() = 0; private: };

Point 1

continue

Polymorphism

QF002/11/9

void Rectangle::Draw() { for (int i = 0; i<itsLength; i++) { for (int j = 0; j<itsWidth; j++) cout << "x "; cout << "\n"; } Shape::Draw(); } class Square : public Rectangle { public: Square(int len); Square(int len, int width); ~Square(){} long GetPerim() {return 4 * GetLength();} }; Square::Square(int len): Rectangle(len,len) {} Square::Square(int len, int width): Rectangle(len,width) { if (GetLength() != GetWidth()) cout << "Error, not a square... a Rectangle??\n"; } int main() { int choice; BOOL fQuit = FALSE; Shape * sp;

continue

Polymorphism

QF002/11/10

void Shape::Draw() { cout << "Abstract drawing mechanism! \n"; } class Circle : public Shape { public: Circle(int radius):itsRadius(radius){} ~Circle(){} long GetArea() { return 3 * itsRadius * itsRadius; } long GetPerim() { return 9 * itsRadius; } void Draw(); private: int itsRadius; int itsCircumference; }; void Circle::Draw() { cout << "Circle drawing routine here! \n"; Shape::Draw(); } class Rectangle : public Shape { public: Rectangle(int len, int width): itsLength(len), itsWidth(width){} ~Rectangle(){} long GetArea() { return itsLength * itsWidth; } long GetPerim() {return 2*its Length + 2*itsWidth; } virtual int GetLength() { return itsLength; } virtual int GetWidth() { return itsWidth; } void Draw(); private: int itsWidth; int itsLength; };

continue

Polymorphism

QF002/11/11

{ for (int i = 0; i<itsLength; i++) { for (int j = 0; j<itsWidth; j++) cout << "x "; cout << "\n"; } Shape::Draw(); } class Square : public Rectangle { public: Square(int len); Square(int len, int width); ~Square(){} long GetPerim() {return 4 * GetLength();} }; Square::Square(int len): Rectangle(len,len) {} Square::Square(int len, in t width): Rectangle(len,width) { if (GetLength() != GetWidth()) cout << "Error, not a square... a Rectangle??\n"; } int main() { int choice; BOOL fQuit = FALSE; Shape * sp;

continue

Polymorphism

QF002/11/12

while (1) { cout << "(1)Circle (2)Rectangle (3)Square (0)Quit: "; cin >> choice; switch (choice) { case 1: sp = new break; case 2: sp = new break; case 3: sp = new break; default: fQuit = break; } if (fQuit) break; sp->Draw(); cout << "\n"; } return 0; }

Circle(5); Rectangle(4,6); Square (5); TRUE;

Figure11.6 :An Example of Program Virtual Function Note: An abstract data type Shape is declared with all three of its accessor methods declared to be pure virtual . The Getarea() and GetPerim() methods are not implemented but Draw() is. The Circle and Rectangle both override Draw() and both chained up to the base method, taking advantage of shared functionality in the base class.

Polymorphism

QF002/11/13

Figure11.7 :An Example Of The Output

11.6

Virtual Table

A virtual table (VTABLE) holds pointers to all the virtual functions in a class. A virtual function pointer (VPTP) is stored within each object. When a derived class accesses a virtual member function, the class looks in the VTABLE to find out which version of the function it should call.

In the case of the Ppoly and PDerived classes defined in 10.2 earlier, their relationships are as follows:

a. A PDerived object is a Ppoly object. b. A PDerived object contains a Ppoly object. c. A Ppoly object can become a PDerived object.

Polymorphism

QF002/11/14

As an example, the following is a Ppoly object and calling


func1(), the VPTR point to the virtual func1() function in

the class as shown below in figure 11.8.

Ppoly *obj = new Ppoly obj func1(); // the Ppoly VPTR points to Ppoly::func1 () Figure11.8:An Example Of Virtual Function Pointer  VPTR in arrangement can be represented graphically as below Internally, the Ppoly VPTR points to the virtual function Func1( ), its only an alternative
VPTR VPTR Ppoly Ppoly::func1()

F igure11.9: A Graphical Example Of VPTR In Arrangement

The virtual function pointer in the Ppoly class point to its only alternative, Ppoly : : func1( )

Polymorphism

QF002/11/15

A PDerived objects VPTR can point to either the Ppoly or PDerived version of func1() at runtime, depending on the circumstances. For example , the PDerived object obj could call the Ppoly version of func1() by specifying that version explicitly as shown below in figure 11.10.

PDerived *obj = new PDerived. Obj Ppoly ::func1();//calls the inherited poly::func1 ()

Figure11.10:An Example Of Virtual Function Pointer PDerived can be represented graphically as below; Internally, the Ppoly VPTR points to the virtual function Func1( ), its only alternative
VPTR VPTR PDerived PDerived ::func1() PDerived object looks into its class VTABLE, finds Poly : : func1(), and then assigns the address of the inherited function to the PDerived VPTR

Ppoly Ppoly::func1()

Figure11.1 : A Graphical Example Of VPTR In Arrangement

Polymorphism

QF002/11/16

Activity 11

Test your comprehension before continuing the next input. Check your answers on the next page.

11.1. 11.2. 11.3.

What is a down cast? What is v-ptr? If a round rectangle has straight edges and rounded corners, your RoundRect class inherits both from Rectangle and from circle and they in turn both inherit from Shape, how many Shapes are created when you create a RoundRect?

11.4.

If a horse and a bird inherit virtual public from Animal, do their constructors initialize the animal constructor? If pegasus inherits from both horse and bird, how does it initialize animal's constructor?

11.5. 11.6.

Declare a class vehicle and make it an abstract data type. If a base class is an ADT and it has three pure virtual functions, how many of these functions must be overridden in its derived classes?

Polymorphism

QF002/11/17

Feedback 11
Make sure you have tried to answer all the questions given. You can check your answers with the answers below.

11.1.

A down cast (also called "casting down") is a declaration that a pointer to a base class is to be treated as a pointer to a derived class. The v-ptr or virtual-function pointer, is an implementation detai l of virtual functions. Each object in a class with virtual functions have a v-ptr which points to the virtual function table for that class. If neither class inherits using the keyword virtual, two shapes are created: one for Rectangle and one for Shape. If the keyword virtual is used for both classes, only one shared shape is created. Both horse and bird initialize their base class, animal in their constructors. Pegasus does as well, and when a pegasus is created, the horse and bird initializations of animal are ignored. class Vehicle { virtual void Move() = 0; }

11.2.

11.3.

11.4.

11.5.

11.6.

None must be overridden unless you want to make the class non abstract in which case all three must be overridden.

Polymorphism

QF002/11/18

Key Facts

 Polymorphism occurs when a single method name, used up and down the hierarchy of objects, acts in an appropriate, possibly different, way for each object.

 Virtual function enables you to call a function depending on the type

of class object.  Remember that you can use an abstract base class only a s a base class for deriving other classes.

Polymorphism

QF002/11/19

Self-Assessment

You are approaching success, please answer the questions below. If you have any problems, please discuss it with your lecturer. Wish you good luck and all the best.

Question

11 - 1

a. Show the declaration for a class jetplane, which inherits from rocket and airplane.

b. Show the declaration for 747 which inherits from the jetplane class described in question a.

c. Show the declarations for the classes car and bus which each derive from the class vehicle. Make the vehicle an ADT with two pure virtual functions. Make car and bus not be ADTs.

d. Modify the program in question c so that car is an ADT and derive sportscar and coupe from car. In the car class, provide an implementation for one of the pure virtual functions in vehicle and make it non-pure.

Polymorphism

QF002/11/20

Feedback On Self-Assessment

Make sure you have tried to answer all the questions given. You can check your answers with the answers below

Answer

11 - 1

a. class JetPlane : public Rocket, public Airplane b. class 747 : public JetPlane c. class Vehicle { virtual void Move() = 0; virtual void Haul() = 0; }; class Car : public Vehicle { virtual void Move(); virtual void Haul(); }; class Bus : public Vehicle { virtual void Move(); virtual void Haul(); };

Polymorphism

QF002/11/21

d. class Vehicle { virtual void Move() = 0; virtual void Haul() = 0; }; class Car : public Vehicle { virtual void Move(); }; class Bus : public Vehicle { virtual void Move(); virtual void Haul(); }; class SportsCar : public Car { virtual void Haul(); }; class Coupe : public Car { virtual void Haul(); };
CONGRATULATION May success be with you always..

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy