[go: up one dir, main page]

0% found this document useful (0 votes)
13 views20 pages

Lecture18-upload

Uploaded by

Aurangzaib Gill
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)
13 views20 pages

Lecture18-upload

Uploaded by

Aurangzaib Gill
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/ 20

Polymorphism

CS 200
Learning Objectives
• Understand the aspects of polymorphism in C++
• Appreciate the need for run time polymorphism
• Practice writing polymorphic code

2
Definition
• Programming: Code exhibiting different behavior
based on context
• What would the method draw() on a Cowboy object do?
• What would the method draw() on a Graphics object do?
• We’ve seen some of it:
• Function overloading
• We’ll see some more of it

3
Types
Polymorphism

Compile-time Run-time

Function
overloading
Operator
overloading
Is function overloading run-time or
Templates
compile-time?

4
5
Run-time Polymorphism
• Run-time polymorphism in C++ requires the
following:
• Inheritance
• Function overriding (a virtual function)
• A pointer or reference variable
• Upcasting

6
Example
• You are working on your e-commerce product

7
Example
Electronics
# warranty: int
Product + Electronics(string,
# name: string int, float, int)
# id: int + getPrice(): float
+ Product(string,
# basePrice: float
int, float)
+ getName(): string
+ getID(): int
+ getPrice(): float Food
+
applyDiscount(float) # expiry: Date
: void + Food(string, int,
float, Date)
+ isSafe(): bool
Let’s code!
8
Summary
• A derived class may redefine an inherited
member function
• At run time:
• May store a derived class object’s pointer in a
pointer to the base class
• However, the base class function will be called
• To get the derived class function called
through base class pointer
• Declare the function as virtual in the base class
Don’t forget to define a virtual destructor
• Add the override keyword to class
in the base the implementation in the
derived class
9
Practice Problems
• Employee, HourlyWage, Salaried, Sales
• pay() virtual method
• PakWheels: Vehicle, Car, Motorbike
• display() virtual method
• Geometry: Shape, Rectangle, Triangle, Square
• area() virtual method

10
Virtual Functions Under The
Hood
class Base {
// Other code
public: Function
virtual void func(); Symbol pointer
// other code func() &Base::func()
};

class Derived : public Base {


// Other code Function
public: Symbol
pointer
&Derived::fun
void func() override; func()
c()
// other code
};

The compiler creates


also creates
a virtual
a (vtable)
table (vtable)
for any class
for any
that
class
overrides
that has
oneone
or
ormore
morevirtual
virtualfunctions
functions 11
Virtual Functions Under The
Hood
Function Function
Symbol Symbol
pointer pointer
&Derived::fun
func() &Base::func() func()
c()

- vptr - vptr - vptr - vptr


- // Other - // Other - // Other - // Other
attributes attributes attributes attributes
Base *b1 = new Base *b2 = new Base *d1 = new Base *d2 = new
Base; Base; Derived; Derived;

TheAny virtualadds
compiler method call looks
a pointer to a up the function
vtable (vptr) toaddress from the
every object of vtable
any such
This pointer points to the respective class’ vtable
through the vptr
classes. 12
Summary
• One vtable for any class that has one or more
virtual functions
• One vptr for every object of such classes
• Points to the vtable for the respective class
• At run-time:
• Virtual method call through a lookup in the vtable
using the vptr

13
Master Chief’s Arsenal
Weapon

# name: string

+ shoot(): void

Every weapon has a unique “shoot”


functionality
There’s no generic “shoot” functionality

AssaultRifle GravityHammer PlasmaGrenade

# clipCapacity: int

+ shoot(): void + shoot(): void + shoot(): void

14
Possible Solutions
• Use methods with different names
• No polymorphism
• Multiple method names are hard to remember
• Implement a dummy shoot() method in the base
class
• Not a clean approach
• Later, someone might add code there causing bugs
• If semantically, it doesn’t make sense, there
shouldn’t be any code there
• Pure virtual function

15
Pure Virtual Functions
• Functions that:
• Are declared as virtual
• Have no implementation
• “= 0” at the end of the function signature
• Corresponding class can’t be instantiated
• Incomplete implementation
• Known as an abstract class
• The opposite is known as a concrete class
• A derived class or may not provide an
implementation
• Can’t instantiate unless it implements all inherited
pure virtual functions
16
Purpose Of An Abstract Class
• What good is an abstract class?
• Creates an “interface” – a contract with a
programmer
• There are usually multiple ways to do the same thing
• Any class can implement a set of pure virtual
functions differently
• Concrete shared members only defined in the
base class

17
Example
Logger

ConsoleLogger FileLogger DBLogger

TextFileLogger CSVFileLogger

Which class(es) should be


abstract? 18
Other Examples
• GUI Frameworks:
• Drawable interface: methods like draw(), resize()
• Payment systems:
• PaymentProcessor interface: methods like authorize(),
refund()
• Database Management System library:
• Connection interface: methods like connect(),
query(), disconnect()
• Multimedia libraries:
• Playable interface: methods like play(), pause(),
stop()
19
Summary
• Runtime polymorphism is implemented with virtual
functions
• Virtual functions work through vtables and vptrs
• A pure virtual function (PVF) is one that has
no implementation
• A class with one or more PVFs is an abstract
class
• An abstract class may not be instantiated

20

You might also like