SlideShare a Scribd company logo
1 of 40
CMSC202
Computer Science II
Lecture 16 -
Polymorphism
Based on slides by Chris Marron, Katie Gibson, and Walter Savitch
CMSC 202 Faculty
Last Class We Covered
• To understand the relationships between objects
• To begin learning about inheritance
• To cover what is being inherited
• To understand how inheritance and
access to member variables interact
2
Any Questions from Last Time?
Today’s Objectives
• To review inheritance
• To learn about overriding
• To begin to understand polymorphism
• Limitations of Inheritance
• Virtual Functions
• Abstract Classes & Function Types
• Virtual Function Tables
• Virtual Destructors/Constructors
4
Next Class
Review of Inheritance
Review of Inheritance
• Specialization through sub classes
• Child class has direct access to
• Parent member functions and variables that are:
• ???
6
Review of Inheritance
• Specialization through sub classes
• Child class has direct access to
• Parent member functions and variables that are:
• Public
• Protected
7
Review of Inheritance
• Specialization through sub classes
• Child class has direct access to
• Parent member functions and variables that are:
• Public
• Protected
• Parent class has direct access to:
• ??????? in the child class
8
Review of Inheritance
• Specialization through sub classes
• Child class has direct access to
• Parent member functions and variables that are:
• Public
• Protected
• Parent class has direct access to:
• Nothing in the child class
9
What is Inherited
• public
members
• protected
members
• private
variables
Parent Class
• private functions
• copy constructor
• assignment operator
• constructor
• destructor
10
Child Class
• child class
members
(functions &
variables)
• public
members
• protected
members
• private
variables
Parent Class
• private functions
• copy constructor
• assignment operator
• constructor
• destructor
11
Replacing a parent function
Specialization
• Child classes are meant to be more specialized than parent classes
• Adding new member functions
• Adding new member variables
• Child classes can also specialize by replacing (or overriding) parent
class member functions
• Child class must use exact same function signature in order to replace (or
override)
13
Replacing vs Overloading
• Overloading
• Use the same function name, but with different parameters for each
overloaded implementation
• Replacing or Overriding
• Use the same function name and parameters, but with a different
implementation
• Child class method “replaces” parent class method
• Child class can call either parent or child version using scope resolution
operator
• Only possible by using inheritance
14
Overriding Examples
• For these examples, the Vehicle class now contains these public
functions:
void Upgrade();
void PrintSpecs();
void Move(double distance);
• Car class inherits all of these public functions
• That means it can therefore replace or override them
• Additionally, an overloaded version could be created as long as there is a
different function signature
15
Basic Overriding Example
• Car class overrides Upgrade()
void Car::Upgrade(){
// entirely new Car-only code
}
• When Upgrade() is called on an object of type Car, what happens?
• The Car::Upgrade() function is invoked
16
Overriding (and Calling) Example
• Car class overrides and calls PrintSpecs()
void Car::PrintSpecs(){
Vehicle::PrintSpecs();
// additional Car-only code
}
• By default, the child class version of the function is called but you can
explicitly call a parent’s original function by using the scope resolution
operator
17
Live Coding
Lec16–> override(driver.cpp, Person.cpp, Student.cpp, makefile)
Overloading
Attempted Overloading Example
• Car class attempts to overload the function
Move(double distance)with new parameters
void Car::Move(double distance,double avgSpeed){
// new overloaded Car-only code
}
• But this does something we weren’t expecting!
20
Precedence
• Overriding takes precedence over overloading
• Instead of overloading the Move() function, the compiler assumes we are
trying to override it
• Declaring Car::Move(2 parameters)
• Overrides Vehicle::Move(1 parameter)
• We no longer have access to the original
Move() function from the Vehicle class
21
Overloading in Child Class
• To overload, we must have both original and
overloaded functions in child class
void Car::Move(double distance);
void Car::Move(double distance,
double avgSpeed);
• The “original” one parameter function can then explicitly call the
parent function
22
Limitations of Inheritance
Car Example
class SUV: public Car {/*etc*/};
class Sedan: public Car {/*etc*/};
class Van: public Car {/*etc*/};
class Jeep: public Car {/*etc*/};
SUV Sedan
Car
Jeep
Van
24
Car Rental Example
• We want to implement a catalog of different types of cars available
for rental
• How could we do this?
• Multiple vectors, one for each type (boo!)
• Combine all the child classes into one giant class with info for every kind of
car (yuck! don’t do this!)
• We can accomplish this with a single vector
• Using polymorphism
25
Polymorphism
What is Polymorphism?
• Ability to manipulate objects in a type-independent way
• Already done to an extent via overriding
• Child class overrides a parent class function
• Can take it further using subtyping, AKA inclusion polymorphism
27
Using Polymorphism
• A pointer of a parent class type can point to an object of a child class
type
Vehicle *vehiclePtr = &myCar;
• Why is this valid?
–Because myCar is-a Vehicle
28
Polymorphism: Car Rental
vector <Car*> rentalList;
vector of Car* objects
29
Polymorphism: Car Rental
vector <Car*> rentalList;
• Can populate the vector with
any of Car’s child classes
SUV SUV Jeep Van Jeep Sedan Sedan SUV
vector of Car* objects
30
Limitations of Polymorphism
• Parent classes do not inherit from child classes
• What about public member variables and functions?
31
Limitations of Polymorphism
• Parent classes do not inherit from child classes
• Not even public member variables and functions
Vehicle *vehiclePtr = &myCar;
• Which version of PrintSpecs() does this call?
vehiclePtr->PrintSpecs();
Vehicle::PrintSpecs()
32
Limitations of Polymorphism
• Parent classes do not inherit from child classes
• Not even public member variables and functions
Vehicle *vehiclePtr = &myCar;
• Will this work?
vehiclePtr->RepaintCar();
– NO! RepaintCar() is a function of the
Car child class, not the Vehicle class
33
Virtual Functions
Virtual Functions
• Can grant access to child methods by using virtual functions
• Virtual functions are how C++ implements
late binding
• Used when the child class implementation is unknown or variable at parent
class creation time
35
Late Binding
• Simply put, binding is determined at run time
– As opposed to at compile time
• In the context of polymorphism, you’re saying
“I don’t know for sure how this function is going to be implemented, so wait
until it’s used and then get the implementation from the object instance.”
36
Using Virtual Functions
• Declare the function in the parent class with the keyword virtual
in front
virtual void Drive();
• Only use virtual with the prototype
// don't do this
virtual void Vehicle::Drive();
37
Using Virtual Functions
• The corresponding child class function does not require the
virtual keyword
• Should still include it, for clarity’s sake
– Makes it obvious the function is virtual,
even without looking at the parent class
// inside the Car class
virtual void Drive();
38
Live Coding
Lec16–> polymorphism1.cpp
Announcements
• Prelab Quizzes (4 pts)
• Released every Friday by 10am on Blackboard
• Due every Monday by 10am on Blackboard
• Lab (6 pts)
• In Engineering building during scheduled time!
• Project 3
• Due on Tuesday, April 2nd at 8:59pm on GL
• Exam 2 Review
• On Friday, April 5th from 2-4pm in ENGR 027
• Exam 2
• In person during your scheduled lecture on Wednesday, April 10th and Thursday, April 11th
40
Next Time: Polymorphism (cont’d)

More Related Content

Similar to CMSC 202 - Lec16 - Polymorphisms(1).pptx

Basics of inheritance .22
Basics of inheritance .22Basics of inheritance .22
Basics of inheritance .22myrajendra
 
2 BytesC++ course_2014_c11_ inheritance
2 BytesC++ course_2014_c11_ inheritance2 BytesC++ course_2014_c11_ inheritance
2 BytesC++ course_2014_c11_ inheritancekinan keshkeh
 
Selenium web driver_2.0_presentation
Selenium web driver_2.0_presentationSelenium web driver_2.0_presentation
Selenium web driver_2.0_presentationsayhi2sudarshan
 
Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3PawanMM
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingRatnaJava
 
Inheritance, Polymorphism, and Virtual Functions.pptx
Inheritance, Polymorphism, and Virtual Functions.pptxInheritance, Polymorphism, and Virtual Functions.pptx
Inheritance, Polymorphism, and Virtual Functions.pptxMrNikhilMohanShinde
 
OOP with Java - Part 3
OOP with Java - Part 3OOP with Java - Part 3
OOP with Java - Part 3Hitesh-Java
 
full defination of final opp.pptx
full defination of final opp.pptxfull defination of final opp.pptx
full defination of final opp.pptxrayanbabur
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract classAmit Trivedi
 
Java Inheritance and Polymorphism
Java Inheritance and PolymorphismJava Inheritance and Polymorphism
Java Inheritance and PolymorphismKadarkaraiSelvam
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptxTansh5
 
Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?GlobalLogic Ukraine
 
2CPP09 - Encapsulation
2CPP09 - Encapsulation2CPP09 - Encapsulation
2CPP09 - EncapsulationMichael Heron
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2Rakesh Madugula
 
Java Encapsulation and Inheritance
Java Encapsulation and Inheritance Java Encapsulation and Inheritance
Java Encapsulation and Inheritance AathikaJava
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++Rabin BK
 

Similar to CMSC 202 - Lec16 - Polymorphisms(1).pptx (20)

Basics of inheritance .22
Basics of inheritance .22Basics of inheritance .22
Basics of inheritance .22
 
2 BytesC++ course_2014_c11_ inheritance
2 BytesC++ course_2014_c11_ inheritance2 BytesC++ course_2014_c11_ inheritance
2 BytesC++ course_2014_c11_ inheritance
 
Selenium web driver_2.0_presentation
Selenium web driver_2.0_presentationSelenium web driver_2.0_presentation
Selenium web driver_2.0_presentation
 
Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Inheritance, Polymorphism, and Virtual Functions.pptx
Inheritance, Polymorphism, and Virtual Functions.pptxInheritance, Polymorphism, and Virtual Functions.pptx
Inheritance, Polymorphism, and Virtual Functions.pptx
 
OOP with Java - Part 3
OOP with Java - Part 3OOP with Java - Part 3
OOP with Java - Part 3
 
Virtual Function
Virtual FunctionVirtual Function
Virtual Function
 
full defination of final opp.pptx
full defination of final opp.pptxfull defination of final opp.pptx
full defination of final opp.pptx
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 
Inheritance
InheritanceInheritance
Inheritance
 
Java Inheritance and Polymorphism
Java Inheritance and PolymorphismJava Inheritance and Polymorphism
Java Inheritance and Polymorphism
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?
 
2CPP09 - Encapsulation
2CPP09 - Encapsulation2CPP09 - Encapsulation
2CPP09 - Encapsulation
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
Java Encapsulation and Inheritance
Java Encapsulation and Inheritance Java Encapsulation and Inheritance
Java Encapsulation and Inheritance
 
Icom4015 lecture8-f16
Icom4015 lecture8-f16Icom4015 lecture8-f16
Icom4015 lecture8-f16
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 

Recently uploaded

Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio, Inc.
 
Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Eraconfluent
 
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Lisi Hocke
 
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Andreas Granig
 
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfThe Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfkalichargn70th171
 
What is a Recruitment Management Software?
What is a Recruitment Management Software?What is a Recruitment Management Software?
What is a Recruitment Management Software?NYGGS Automation Suite
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Soroosh Khodami
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckMarc Lester
 
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
Auto Affiliate  AI Earns First Commission in 3 Hours..pdfAuto Affiliate  AI Earns First Commission in 3 Hours..pdf
Auto Affiliate AI Earns First Commission in 3 Hours..pdfSelfMade bd
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfsteffenkarlsson2
 
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...naitiksharma1124
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In sowetokasambamuno
 
The Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationThe Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationElement34
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabbereGrabber
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Gáspár Nagy
 
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024SimonedeGijt
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In hararekasambamuno
 
Food Delivery Business App Development Guide 2024
Food Delivery Business App Development Guide 2024Food Delivery Business App Development Guide 2024
Food Delivery Business App Development Guide 2024Chirag Panchal
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMarkus Moeller
 
A Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfA Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfICS
 

Recently uploaded (20)

Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
 
Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Era
 
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
 
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
 
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfThe Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
 
What is a Recruitment Management Software?
What is a Recruitment Management Software?What is a Recruitment Management Software?
What is a Recruitment Management Software?
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined Deck
 
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
Auto Affiliate  AI Earns First Commission in 3 Hours..pdfAuto Affiliate  AI Earns First Commission in 3 Hours..pdf
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
 
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
 
The Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationThe Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test Automation
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
 
Food Delivery Business App Development Guide 2024
Food Delivery Business App Development Guide 2024Food Delivery Business App Development Guide 2024
Food Delivery Business App Development Guide 2024
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdf
 
A Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfA Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdf
 

CMSC 202 - Lec16 - Polymorphisms(1).pptx

  • 1. CMSC202 Computer Science II Lecture 16 - Polymorphism Based on slides by Chris Marron, Katie Gibson, and Walter Savitch CMSC 202 Faculty
  • 2. Last Class We Covered • To understand the relationships between objects • To begin learning about inheritance • To cover what is being inherited • To understand how inheritance and access to member variables interact 2
  • 3. Any Questions from Last Time?
  • 4. Today’s Objectives • To review inheritance • To learn about overriding • To begin to understand polymorphism • Limitations of Inheritance • Virtual Functions • Abstract Classes & Function Types • Virtual Function Tables • Virtual Destructors/Constructors 4 Next Class
  • 6. Review of Inheritance • Specialization through sub classes • Child class has direct access to • Parent member functions and variables that are: • ??? 6
  • 7. Review of Inheritance • Specialization through sub classes • Child class has direct access to • Parent member functions and variables that are: • Public • Protected 7
  • 8. Review of Inheritance • Specialization through sub classes • Child class has direct access to • Parent member functions and variables that are: • Public • Protected • Parent class has direct access to: • ??????? in the child class 8
  • 9. Review of Inheritance • Specialization through sub classes • Child class has direct access to • Parent member functions and variables that are: • Public • Protected • Parent class has direct access to: • Nothing in the child class 9
  • 10. What is Inherited • public members • protected members • private variables Parent Class • private functions • copy constructor • assignment operator • constructor • destructor 10
  • 11. Child Class • child class members (functions & variables) • public members • protected members • private variables Parent Class • private functions • copy constructor • assignment operator • constructor • destructor 11
  • 12. Replacing a parent function
  • 13. Specialization • Child classes are meant to be more specialized than parent classes • Adding new member functions • Adding new member variables • Child classes can also specialize by replacing (or overriding) parent class member functions • Child class must use exact same function signature in order to replace (or override) 13
  • 14. Replacing vs Overloading • Overloading • Use the same function name, but with different parameters for each overloaded implementation • Replacing or Overriding • Use the same function name and parameters, but with a different implementation • Child class method “replaces” parent class method • Child class can call either parent or child version using scope resolution operator • Only possible by using inheritance 14
  • 15. Overriding Examples • For these examples, the Vehicle class now contains these public functions: void Upgrade(); void PrintSpecs(); void Move(double distance); • Car class inherits all of these public functions • That means it can therefore replace or override them • Additionally, an overloaded version could be created as long as there is a different function signature 15
  • 16. Basic Overriding Example • Car class overrides Upgrade() void Car::Upgrade(){ // entirely new Car-only code } • When Upgrade() is called on an object of type Car, what happens? • The Car::Upgrade() function is invoked 16
  • 17. Overriding (and Calling) Example • Car class overrides and calls PrintSpecs() void Car::PrintSpecs(){ Vehicle::PrintSpecs(); // additional Car-only code } • By default, the child class version of the function is called but you can explicitly call a parent’s original function by using the scope resolution operator 17
  • 18. Live Coding Lec16–> override(driver.cpp, Person.cpp, Student.cpp, makefile)
  • 20. Attempted Overloading Example • Car class attempts to overload the function Move(double distance)with new parameters void Car::Move(double distance,double avgSpeed){ // new overloaded Car-only code } • But this does something we weren’t expecting! 20
  • 21. Precedence • Overriding takes precedence over overloading • Instead of overloading the Move() function, the compiler assumes we are trying to override it • Declaring Car::Move(2 parameters) • Overrides Vehicle::Move(1 parameter) • We no longer have access to the original Move() function from the Vehicle class 21
  • 22. Overloading in Child Class • To overload, we must have both original and overloaded functions in child class void Car::Move(double distance); void Car::Move(double distance, double avgSpeed); • The “original” one parameter function can then explicitly call the parent function 22
  • 24. Car Example class SUV: public Car {/*etc*/}; class Sedan: public Car {/*etc*/}; class Van: public Car {/*etc*/}; class Jeep: public Car {/*etc*/}; SUV Sedan Car Jeep Van 24
  • 25. Car Rental Example • We want to implement a catalog of different types of cars available for rental • How could we do this? • Multiple vectors, one for each type (boo!) • Combine all the child classes into one giant class with info for every kind of car (yuck! don’t do this!) • We can accomplish this with a single vector • Using polymorphism 25
  • 27. What is Polymorphism? • Ability to manipulate objects in a type-independent way • Already done to an extent via overriding • Child class overrides a parent class function • Can take it further using subtyping, AKA inclusion polymorphism 27
  • 28. Using Polymorphism • A pointer of a parent class type can point to an object of a child class type Vehicle *vehiclePtr = &myCar; • Why is this valid? –Because myCar is-a Vehicle 28
  • 29. Polymorphism: Car Rental vector <Car*> rentalList; vector of Car* objects 29
  • 30. Polymorphism: Car Rental vector <Car*> rentalList; • Can populate the vector with any of Car’s child classes SUV SUV Jeep Van Jeep Sedan Sedan SUV vector of Car* objects 30
  • 31. Limitations of Polymorphism • Parent classes do not inherit from child classes • What about public member variables and functions? 31
  • 32. Limitations of Polymorphism • Parent classes do not inherit from child classes • Not even public member variables and functions Vehicle *vehiclePtr = &myCar; • Which version of PrintSpecs() does this call? vehiclePtr->PrintSpecs(); Vehicle::PrintSpecs() 32
  • 33. Limitations of Polymorphism • Parent classes do not inherit from child classes • Not even public member variables and functions Vehicle *vehiclePtr = &myCar; • Will this work? vehiclePtr->RepaintCar(); – NO! RepaintCar() is a function of the Car child class, not the Vehicle class 33
  • 35. Virtual Functions • Can grant access to child methods by using virtual functions • Virtual functions are how C++ implements late binding • Used when the child class implementation is unknown or variable at parent class creation time 35
  • 36. Late Binding • Simply put, binding is determined at run time – As opposed to at compile time • In the context of polymorphism, you’re saying “I don’t know for sure how this function is going to be implemented, so wait until it’s used and then get the implementation from the object instance.” 36
  • 37. Using Virtual Functions • Declare the function in the parent class with the keyword virtual in front virtual void Drive(); • Only use virtual with the prototype // don't do this virtual void Vehicle::Drive(); 37
  • 38. Using Virtual Functions • The corresponding child class function does not require the virtual keyword • Should still include it, for clarity’s sake – Makes it obvious the function is virtual, even without looking at the parent class // inside the Car class virtual void Drive(); 38
  • 40. Announcements • Prelab Quizzes (4 pts) • Released every Friday by 10am on Blackboard • Due every Monday by 10am on Blackboard • Lab (6 pts) • In Engineering building during scheduled time! • Project 3 • Due on Tuesday, April 2nd at 8:59pm on GL • Exam 2 Review • On Friday, April 5th from 2-4pm in ENGR 027 • Exam 2 • In person during your scheduled lecture on Wednesday, April 10th and Thursday, April 11th 40 Next Time: Polymorphism (cont’d)