SlideShare a Scribd company logo
1 of 17
Download to read offline
Object-Oriented Programming
in C++
Lecture 7
Polymorphism
Introduction
Last lecture we
•reviewed the concept of inheritance
•discussed how to implement inheritance in
C++
This lecture we will
•introduce polymorphism
•explain virtual and pure virtual functions
•learn how to use polymorphism in C++
programs
LandVehicl
e
+move()
Polymorphism
• many forms
• Greek
– "poly" – many
– "morph" form
• the same method can
be called on different
objects
• they may respond to it
in different ways
• all Vehicles have a
move method
• Cars and Truck drive
• Airplanes fly
Vehicle
+move()
Airplane
+move()
Car Truck
Polymorphism example
• see handout for implementation of Vehicle class hierarchy
#include "Vehicle.h"
int main(){
Vehicle v ("Transporter 54");
Airplane a("Tornado 2431", 14);
LandVehicle lv("My wheels");
Car c("Ford Anglia 22");
Truck t("Red pickup");
v.move();
a.move();
lv.move();
c.move();
t.move();
}
Output
Vehicle constructor
Vehicle constructor
Airplane constructor
Vehicle constructor
Land vehicle constructor
Vechicle constructor
Land vehicle constructor
Car constructor
Vechicle constructor
Land vehicle constructor
Truck constructor
Vehicle Transporter 54
moving
Airplane Tornado 2431
flying
Land Vehicle My wheels
driving
Land Vehicle Ford Anglia
22 driving
Land Vehicle Red pickup
driving
Which version of move is called
• in the previous example, the version of
move to be called was determined at
compile time
– depends on the object type
– for Airplane a, the Airplane version of move
– for Car c, the Vehicle version of move
• what about a situation where the type is
not known at compile time?
#include "Vehicle.h"
void moveVehicle(Vehicle * v) {
v->move();
}
int main(){
Vehicle v ("Transporter 54");
Airplane a("Tornado 2431", 14);
LandVehicle lv("My wheels");
Car c("Ford Anglia 22");
Truck t("Red pickup");
moveVehicle(&v);
moveVehicle(&a);
moveVehicle(&lv);
moveVehicle(&c);
moveVehicle(&t);
}
Output
….
Vehicle Transporter
54 moving
Vehicle Tornado 2431
moving
Vehicle My wheels
moving
Vehicle Ford Anglia
22 moving
Vehicle Red pickup
moving
• the moveVehicle
method takes a pointer to
any Vehicle object
• which could be any
subtype of Vehicle
• however, the move
method to call is
determined at compile
time
– Vehicle version
• all vehicles move the
same way
Polymorphic behaviour
• to get polymorphic behaviour, we would like the version
of move() to be determined at run-time
• if moveVehicle is sent an Airplane object, it should
get it to fly
• do this by using the virtual keyword in the first (base
class) declaration of the polymorphic method
class Vehicle {
protected:
string name;
public:
// other members
virtual void move() { cout << "Vehicle "
<< name << " moving" << endl; }
};
• now it works
Polymorphic output
Vehicle Transporter 54 moving
Airplane Tornado 2431 flying
Land Vehicle My wheels driving
Land Vehicle Ford Anglia 22 driving
Land Vehicle Red pickup driving
Polymorphism
• polymorphism allows us to use a pointer to
a derived type object wherever a pointer to
base type is expected
Car c("Ford Anglia 22");
Vehicle * v2 = &c;
v2->move();
Vehicle & v3 = c;
v3.move();
• only works for pointer and reference types
• they store an address – same size for all objects
Land Vehicle Ford Anglia 22 driving
Land Vehicle Ford Anglia 22 driving
This won't work
Airplane a("Tornado 2431", 14);
Vehicle v2 = a;
v2.move();
• trying to fit an airplane into a space meant
for any vehicle
• can call the move() method, but we've lost
the wingspan member variable
Virtual destructors
• constructors cannot be virtual
– the correct one is always called anyway
• destructors can be virtual
• you should specify a virtual destructor for
any class which is overridden
• so that the object is cleaned up correctly
• otherwise you might not deallocate all the
memory allocated to a subclass object
Pure virtual functions
• sometimes it is not sensible to implement a base
class virtual function
• how does a Vehicle move?
• a pure virtual function does not have an
implementation
• virtual void move() =0;
• the subclasses must implement it
• a class with a pure virtual function cannot be
instantiated
– if we made it virtual, how would it move?
• such a class is abstract
Comparison to Java
• in Java, all methods are virtual by default
• the keyword abstract is used to define
pure virtual functions
• a class containing an abstract method
must itself be abstract
• C++ is more flexible but can be confusing
– why have virtual and non-virtual functions?
Virtual functions
• using a virtual function has an overhead
• the correct method cannot be bound to a
method call at compile time
• it is determined at run-time by looking up
the correct method address in a table
• this takes up time and space
• if polymorphism is not being used, this is
expensive.
Summary
In this lecture we have:
•introduced polymorphism
•explained virtual and pure virtual functions
•learned how to use polymorphism in C++
programs

More Related Content

Similar to c++ polymorphism.ppt

Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsRobert Brown
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java introkabirmahlotra
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java introkabirmahlotra
 
2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation FundamentalsMichael Heron
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming IntroLou Loizides
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLou Loizides
 
Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patternsJeremy Duvall
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
Using traits in PHP
Using traits in PHPUsing traits in PHP
Using traits in PHPMaksym Hopei
 
Inheritance and Polymorphism in Oops
Inheritance and Polymorphism in OopsInheritance and Polymorphism in Oops
Inheritance and Polymorphism in OopsLalfakawmaKh
 
Racing car katas Ⅲ - Static Cling
Racing car katas Ⅲ - Static ClingRacing car katas Ⅲ - Static Cling
Racing car katas Ⅲ - Static ClingGeorg Berky
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
Functional Programming in Clojure
Functional Programming in ClojureFunctional Programming in Clojure
Functional Programming in ClojureTroy Miles
 
Swift, a quick overview
Swift, a quick overviewSwift, a quick overview
Swift, a quick overviewJulian Król
 

Similar to c++ polymorphism.ppt (20)

Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
 
Swift for-rubyists
Swift for-rubyistsSwift for-rubyists
Swift for-rubyists
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java intro
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java intro
 
UNIT IV (1).ppt
UNIT IV (1).pptUNIT IV (1).ppt
UNIT IV (1).ppt
 
2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals2CPP03 - Object Orientation Fundamentals
2CPP03 - Object Orientation Fundamentals
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming Intro
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming Introduction
 
Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patterns
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Using traits in PHP
Using traits in PHPUsing traits in PHP
Using traits in PHP
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Inheritance and Polymorphism in Oops
Inheritance and Polymorphism in OopsInheritance and Polymorphism in Oops
Inheritance and Polymorphism in Oops
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Polymorphismupload
PolymorphismuploadPolymorphismupload
Polymorphismupload
 
Racing car katas Ⅲ - Static Cling
Racing car katas Ⅲ - Static ClingRacing car katas Ⅲ - Static Cling
Racing car katas Ⅲ - Static Cling
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Functional Programming in Clojure
Functional Programming in ClojureFunctional Programming in Clojure
Functional Programming in Clojure
 
Swift, a quick overview
Swift, a quick overviewSwift, a quick overview
Swift, a quick overview
 

Recently uploaded

2024_hackersuli_mobil_ios_android ______
2024_hackersuli_mobil_ios_android ______2024_hackersuli_mobil_ios_android ______
2024_hackersuli_mobil_ios_android ______hackersuli
 
IPv6 Operational Issues (with DNS), presented by Geoff Huston at IETF 119
IPv6 Operational Issues (with DNS), presented by Geoff Huston at IETF 119IPv6 Operational Issues (with DNS), presented by Geoff Huston at IETF 119
IPv6 Operational Issues (with DNS), presented by Geoff Huston at IETF 119APNIC
 
draft-harrison-sidrops-manifest-number-01, presented at IETF 119
draft-harrison-sidrops-manifest-number-01, presented at IETF 119draft-harrison-sidrops-manifest-number-01, presented at IETF 119
draft-harrison-sidrops-manifest-number-01, presented at IETF 119APNIC
 
Cyber Shield Up - They Shall Not Pass - Andreas Sfakianakis - Lecture at CSD ...
Cyber Shield Up - They Shall Not Pass - Andreas Sfakianakis - Lecture at CSD ...Cyber Shield Up - They Shall Not Pass - Andreas Sfakianakis - Lecture at CSD ...
Cyber Shield Up - They Shall Not Pass - Andreas Sfakianakis - Lecture at CSD ...Andreas Sfakianakis
 
Making an RFC in Today's IETF, presented by Geoff Huston at IETF 119
Making an RFC in Today's IETF, presented by Geoff Huston at IETF 119Making an RFC in Today's IETF, presented by Geoff Huston at IETF 119
Making an RFC in Today's IETF, presented by Geoff Huston at IETF 119APNIC
 
Power of Social Media for E-commerce.pdf
Power of Social Media for E-commerce.pdfPower of Social Media for E-commerce.pdf
Power of Social Media for E-commerce.pdfrajats19920
 
Tari Eason Warriors Come Out To Play T Shirts
Tari Eason Warriors Come Out To Play T ShirtsTari Eason Warriors Come Out To Play T Shirts
Tari Eason Warriors Come Out To Play T Shirtsrahman018755
 
Basic Security.pptx is a awsome PPT on your mobiel
Basic Security.pptx is a awsome PPT on your mobielBasic Security.pptx is a awsome PPT on your mobiel
Basic Security.pptx is a awsome PPT on your mobielpratamakiki860
 
IP addressing and IPv6, presented by Paul Wilson at IETF 119
IP addressing and IPv6, presented by Paul Wilson at IETF 119IP addressing and IPv6, presented by Paul Wilson at IETF 119
IP addressing and IPv6, presented by Paul Wilson at IETF 119APNIC
 
Summary ID-IGF 2016 National Dialogue - English (tata kelola internet / int...
Summary  ID-IGF 2016 National Dialogue  - English (tata kelola internet / int...Summary  ID-IGF 2016 National Dialogue  - English (tata kelola internet / int...
Summary ID-IGF 2016 National Dialogue - English (tata kelola internet / int...ICT Watch - Indonesia
 
办理澳洲USYD文凭证书学历认证【Q微/1954292140】办理悉尼大学毕业证书真实成绩单GPA修改/办理澳洲大学文凭证书Offer录取通知书/在读证明...
办理澳洲USYD文凭证书学历认证【Q微/1954292140】办理悉尼大学毕业证书真实成绩单GPA修改/办理澳洲大学文凭证书Offer录取通知书/在读证明...办理澳洲USYD文凭证书学历认证【Q微/1954292140】办理悉尼大学毕业证书真实成绩单GPA修改/办理澳洲大学文凭证书Offer录取通知书/在读证明...
办理澳洲USYD文凭证书学历认证【Q微/1954292140】办理悉尼大学毕业证书真实成绩单GPA修改/办理澳洲大学文凭证书Offer录取通知书/在读证明...vmzoxnx5
 
Summary IGF 2013 Bali - English (tata kelola internet / internet governance)
Summary  IGF 2013 Bali - English (tata kelola internet / internet governance)Summary  IGF 2013 Bali - English (tata kelola internet / internet governance)
Summary IGF 2013 Bali - English (tata kelola internet / internet governance)ICT Watch - Indonesia
 
Is DNS ready for IPv6, presented by Geoff Huston at IETF 119
Is DNS ready for IPv6, presented by Geoff Huston at IETF 119Is DNS ready for IPv6, presented by Geoff Huston at IETF 119
Is DNS ready for IPv6, presented by Geoff Huston at IETF 119APNIC
 

Recently uploaded (13)

2024_hackersuli_mobil_ios_android ______
2024_hackersuli_mobil_ios_android ______2024_hackersuli_mobil_ios_android ______
2024_hackersuli_mobil_ios_android ______
 
IPv6 Operational Issues (with DNS), presented by Geoff Huston at IETF 119
IPv6 Operational Issues (with DNS), presented by Geoff Huston at IETF 119IPv6 Operational Issues (with DNS), presented by Geoff Huston at IETF 119
IPv6 Operational Issues (with DNS), presented by Geoff Huston at IETF 119
 
draft-harrison-sidrops-manifest-number-01, presented at IETF 119
draft-harrison-sidrops-manifest-number-01, presented at IETF 119draft-harrison-sidrops-manifest-number-01, presented at IETF 119
draft-harrison-sidrops-manifest-number-01, presented at IETF 119
 
Cyber Shield Up - They Shall Not Pass - Andreas Sfakianakis - Lecture at CSD ...
Cyber Shield Up - They Shall Not Pass - Andreas Sfakianakis - Lecture at CSD ...Cyber Shield Up - They Shall Not Pass - Andreas Sfakianakis - Lecture at CSD ...
Cyber Shield Up - They Shall Not Pass - Andreas Sfakianakis - Lecture at CSD ...
 
Making an RFC in Today's IETF, presented by Geoff Huston at IETF 119
Making an RFC in Today's IETF, presented by Geoff Huston at IETF 119Making an RFC in Today's IETF, presented by Geoff Huston at IETF 119
Making an RFC in Today's IETF, presented by Geoff Huston at IETF 119
 
Power of Social Media for E-commerce.pdf
Power of Social Media for E-commerce.pdfPower of Social Media for E-commerce.pdf
Power of Social Media for E-commerce.pdf
 
Tari Eason Warriors Come Out To Play T Shirts
Tari Eason Warriors Come Out To Play T ShirtsTari Eason Warriors Come Out To Play T Shirts
Tari Eason Warriors Come Out To Play T Shirts
 
Basic Security.pptx is a awsome PPT on your mobiel
Basic Security.pptx is a awsome PPT on your mobielBasic Security.pptx is a awsome PPT on your mobiel
Basic Security.pptx is a awsome PPT on your mobiel
 
IP addressing and IPv6, presented by Paul Wilson at IETF 119
IP addressing and IPv6, presented by Paul Wilson at IETF 119IP addressing and IPv6, presented by Paul Wilson at IETF 119
IP addressing and IPv6, presented by Paul Wilson at IETF 119
 
Summary ID-IGF 2016 National Dialogue - English (tata kelola internet / int...
Summary  ID-IGF 2016 National Dialogue  - English (tata kelola internet / int...Summary  ID-IGF 2016 National Dialogue  - English (tata kelola internet / int...
Summary ID-IGF 2016 National Dialogue - English (tata kelola internet / int...
 
办理澳洲USYD文凭证书学历认证【Q微/1954292140】办理悉尼大学毕业证书真实成绩单GPA修改/办理澳洲大学文凭证书Offer录取通知书/在读证明...
办理澳洲USYD文凭证书学历认证【Q微/1954292140】办理悉尼大学毕业证书真实成绩单GPA修改/办理澳洲大学文凭证书Offer录取通知书/在读证明...办理澳洲USYD文凭证书学历认证【Q微/1954292140】办理悉尼大学毕业证书真实成绩单GPA修改/办理澳洲大学文凭证书Offer录取通知书/在读证明...
办理澳洲USYD文凭证书学历认证【Q微/1954292140】办理悉尼大学毕业证书真实成绩单GPA修改/办理澳洲大学文凭证书Offer录取通知书/在读证明...
 
Summary IGF 2013 Bali - English (tata kelola internet / internet governance)
Summary  IGF 2013 Bali - English (tata kelola internet / internet governance)Summary  IGF 2013 Bali - English (tata kelola internet / internet governance)
Summary IGF 2013 Bali - English (tata kelola internet / internet governance)
 
Is DNS ready for IPv6, presented by Geoff Huston at IETF 119
Is DNS ready for IPv6, presented by Geoff Huston at IETF 119Is DNS ready for IPv6, presented by Geoff Huston at IETF 119
Is DNS ready for IPv6, presented by Geoff Huston at IETF 119
 

c++ polymorphism.ppt

  • 2. Introduction Last lecture we •reviewed the concept of inheritance •discussed how to implement inheritance in C++ This lecture we will •introduce polymorphism •explain virtual and pure virtual functions •learn how to use polymorphism in C++ programs
  • 3. LandVehicl e +move() Polymorphism • many forms • Greek – "poly" – many – "morph" form • the same method can be called on different objects • they may respond to it in different ways • all Vehicles have a move method • Cars and Truck drive • Airplanes fly Vehicle +move() Airplane +move() Car Truck
  • 4. Polymorphism example • see handout for implementation of Vehicle class hierarchy #include "Vehicle.h" int main(){ Vehicle v ("Transporter 54"); Airplane a("Tornado 2431", 14); LandVehicle lv("My wheels"); Car c("Ford Anglia 22"); Truck t("Red pickup"); v.move(); a.move(); lv.move(); c.move(); t.move(); }
  • 5. Output Vehicle constructor Vehicle constructor Airplane constructor Vehicle constructor Land vehicle constructor Vechicle constructor Land vehicle constructor Car constructor Vechicle constructor Land vehicle constructor Truck constructor Vehicle Transporter 54 moving Airplane Tornado 2431 flying Land Vehicle My wheels driving Land Vehicle Ford Anglia 22 driving Land Vehicle Red pickup driving
  • 6. Which version of move is called • in the previous example, the version of move to be called was determined at compile time – depends on the object type – for Airplane a, the Airplane version of move – for Car c, the Vehicle version of move • what about a situation where the type is not known at compile time?
  • 7. #include "Vehicle.h" void moveVehicle(Vehicle * v) { v->move(); } int main(){ Vehicle v ("Transporter 54"); Airplane a("Tornado 2431", 14); LandVehicle lv("My wheels"); Car c("Ford Anglia 22"); Truck t("Red pickup"); moveVehicle(&v); moveVehicle(&a); moveVehicle(&lv); moveVehicle(&c); moveVehicle(&t); }
  • 8. Output …. Vehicle Transporter 54 moving Vehicle Tornado 2431 moving Vehicle My wheels moving Vehicle Ford Anglia 22 moving Vehicle Red pickup moving • the moveVehicle method takes a pointer to any Vehicle object • which could be any subtype of Vehicle • however, the move method to call is determined at compile time – Vehicle version • all vehicles move the same way
  • 9. Polymorphic behaviour • to get polymorphic behaviour, we would like the version of move() to be determined at run-time • if moveVehicle is sent an Airplane object, it should get it to fly • do this by using the virtual keyword in the first (base class) declaration of the polymorphic method class Vehicle { protected: string name; public: // other members virtual void move() { cout << "Vehicle " << name << " moving" << endl; } }; • now it works
  • 10. Polymorphic output Vehicle Transporter 54 moving Airplane Tornado 2431 flying Land Vehicle My wheels driving Land Vehicle Ford Anglia 22 driving Land Vehicle Red pickup driving
  • 11. Polymorphism • polymorphism allows us to use a pointer to a derived type object wherever a pointer to base type is expected Car c("Ford Anglia 22"); Vehicle * v2 = &c; v2->move(); Vehicle & v3 = c; v3.move(); • only works for pointer and reference types • they store an address – same size for all objects Land Vehicle Ford Anglia 22 driving Land Vehicle Ford Anglia 22 driving
  • 12. This won't work Airplane a("Tornado 2431", 14); Vehicle v2 = a; v2.move(); • trying to fit an airplane into a space meant for any vehicle • can call the move() method, but we've lost the wingspan member variable
  • 13. Virtual destructors • constructors cannot be virtual – the correct one is always called anyway • destructors can be virtual • you should specify a virtual destructor for any class which is overridden • so that the object is cleaned up correctly • otherwise you might not deallocate all the memory allocated to a subclass object
  • 14. Pure virtual functions • sometimes it is not sensible to implement a base class virtual function • how does a Vehicle move? • a pure virtual function does not have an implementation • virtual void move() =0; • the subclasses must implement it • a class with a pure virtual function cannot be instantiated – if we made it virtual, how would it move? • such a class is abstract
  • 15. Comparison to Java • in Java, all methods are virtual by default • the keyword abstract is used to define pure virtual functions • a class containing an abstract method must itself be abstract • C++ is more flexible but can be confusing – why have virtual and non-virtual functions?
  • 16. Virtual functions • using a virtual function has an overhead • the correct method cannot be bound to a method call at compile time • it is determined at run-time by looking up the correct method address in a table • this takes up time and space • if polymorphism is not being used, this is expensive.
  • 17. Summary In this lecture we have: •introduced polymorphism •explained virtual and pure virtual functions •learned how to use polymorphism in C++ programs