SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
POLYMORPHISM
Michael Heron
Introduction
• The last of the three fundamental pillars of object
orientation is the principle of polymorphism.
• It’s also the most abstract and difficult to initially see the benefits of.
• In the C++ model of polymorphism, it is inextricably tied
up in the idea of inheritance.
• They go together, hand in hand.
Polymorphism
• The word Polymorphism comes from the Greek.
• Poly meaning ‘parrot’
• Morph meaning ‘small man made of plasticine’.
• In basic terms, it means:
• To treat a specialised object as an instance of its more general
case.
• For example, a Circle is a Circle.
• But in a more general way, it’s also a shape.
The Scenario
• We’re going to explore the topic of polymorphism through
a simple example program.
• It relates to the relationship between two classes – an Employee
and a Manager.
• They are very similar except:
• Managers can hire and fire
• Employees cannot.
The Employee Class
class Employee {
private:
int payscale;
public:
int query_payscale();
void set_payscale (int p);
bool can_hire_and_fire();
};
#include "Employee.h"
bool Employee::can_hire_and_fire(){
return false;
}
void Employee::set_payscale(int val) {
payscale = val;
}
int Employee::query_payscale() {
return payscale;
}
The Manager Class
class Manager : public Employee {
public:
bool can_hire_and_fire();
};
#include "Manager.h"
bool Manager::can_hire_and_fire() {
return true;
}
The Program
#include <iostream>
#include "Employee.h"
#include "Manager.h"
using namespace std;
int main(int argc, char** argv) {
Employee *emp = new Employee();
Manager *man = new Manager();
cout << "Employees hiring and firing rights:" << emp-
>can_hire_and_fire() << endl;
cout << "Managerss hiring and firing rights:" << man-
>can_hire_and_fire() << endl;
return 1
}
The Output
• So far, it’s pretty straightforward.
• Output for employees is 0.
• False
• Output for managers is 1.
• True.
• So it is written, so shall it be.
• The polymorphism comes in when when we want to do something
a little more arcane.
• Make a pointer to a base class point to am object of a more specialised
class.
Polymorphism
#include <iostream>
#include "Employee.h"
#include "Manager.h"
using namespace std;
int main(int argc, char** argv) {
Employee *emp = new Employee();
Manager *man = new Manager();
Employee *poly = new Manager();
cout << "Employees hiring and firing rights:" << emp->can_hire_and_fire() <<
endl;
cout << "Managers hiring and firing rights:" << man->can_hire_and_fire() <<
endl;
cout << "Polymorphic hiring and firing rights:" << poly-
>can_hire_and_fire() << endl;
return 1;
}
And…?
• What happens now?
• In Java, it calls the most specialised version of the method.
• It would call the one defined in Manager.
• In C++, it calls the method as defined in the class that is referenced
by the pointer.
• It would call the one defined in Employee.
• Okay, great – but so what?
The Power
• The power comes from when we have many different
classes that extend from a common core.
• Rather than coding special conditions for each of them, we code for
the base class.
• This greatly reduces the amount of work that a developer
has to do.
• And properly distributes the responsibility for implementing
functionality.
Virtual Functions
• However, much of this is based on the idea that we can
trust a generalised reference to execute the most
appropriate method.
• As is done in Java
• C++ requires us to define a function as virtual if we want
this behaviour.
• From this point on, it becomes a virtual function and behaves in
the way we would expect from Java.
Modified Class Definition
class Employee {
private:
int payscale;
public:
int query_payscale();
void set_payscale (int p);
virtual bool can_hire_and_fire();
};
How Do Virtuals Work?
• When an object is created from a class, C++ creates a lookup
table for virtual functions.
• This is in addition to all other data stored.
• Each virtual function has an entry in this table.
• When you create the object with new, the entry is updated with a
reference to the appropriately specialized implementation.
• Each virtual method you declare increases the size of this
table.
• And thus size of the objects and processing time.
Clerical Staff
#include "Employee.h"
class Clerical: public Employee {
public:
bool can_hire_and_fire();
void file_papers();
};
#include "Clerical.h"
bool Clerical::can_hire_and_fire() {
return false;
}
void Clerical::file_papers() {
// Something Something
}
Modified Scenario
• Two classes stem from the same root.
• Employee
• Using the Power of Polymorphism, we can treat them as
instances of the base class.
• We can manipulate them as if they were just Employees.
• This means that we can’t make use of methods defined in the
specialised classes.
• Only what we can guarantee is implemented by virtue of the class
hierarchy.
New Code
using namespace std;
void set_payscale (Employee* emp, float amount) {
emp->set_payscale (amount);
}
int main(int argc, char** argv) {
Employee *emp = new Employee();
Manager *man = new Manager();
Clerical *cler = new Clerical();
cout << "Employees hiring and firing rights:" << emp->can_hire_and_fire() << endl;
cout << "Managers hiring and firing rights:" << man->can_hire_and_fire() << endl;
cout << "Clerical hiring and firing rights:" << cler->can_hire_and_fire() << endl;
set_payscale (cler, 15000.0);
set_payscale (man, 25000.0);
cout << "Clerical payscale: " << cler->query_payscale() << endl;
cout << "Manager payscale: " << man->query_payscale() << endl;
return 1;
}
The Employee Class
• The Employee class is now something we don’t really
want people using it.
• It’s a common core, not a fully fledged object in its own right.
• In the next lecture, we’ll look at how we can prevent
people making use of it directly.
• We’ll also look at ways other than inheritance to provide a structure
for objects.
Benefits of Polymorphism
• One of the benefits that comes from polymorphism is the
ease of processing lists of objects.
• We don’t need a separate queue for Managers and Clerical staff
• We just need one queue of employees
• We can iterate over each of these, provided we are
making use of base functions.
Benefits of Polymorphism
using namespace std;
void set_payscale (Employee* emp, float amount) {
emp->set_payscale (amount);
}
int main(int argc, char** argv) {
Employee *emp = new Employee();
Employee **emps = new Employee*[2];
emps[0] = new Manager();
emps[1] = new Clerical();
for (int i = 0; i < 2; i++) {
set_payscale (emps[i], 20000.0);
cout << "Payscale for " << i << " is " << emps[i]->query_payscale() << endl;
}
return 1;
}
Benefits of Polymorphism
• Polymorphism manages the complexity of the inheritance
model and lets you provide custom handling in the classes
themselves.
• You don’t need:
• if (it’s a manager) { do_this(); } else if (it’s a clerical) {
do_this_other_thing() }
• One method, properly designed, can handle all the heavy
lifting.
• This does require the use of a clean, well designed object hierarchy.
Summary
• Polymorphism is the last of the three pillars of object
oriented programming.
• The most powerful, but also the most abstract.
• You’re not really expected to ‘get it’ just yet.
• We’ll return to the topic in later lectures.
• In the next lecture we’re going to continue discussing
some of the ways in which we can enforce structure on
our unruly objects.

Weitere ähnliche Inhalte

Was ist angesagt?

Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type ConversionsRokonuzzaman Rony
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
C++ overloading
C++ overloadingC++ overloading
C++ overloadingsanya6900
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshuSidd Singh
 
pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphismramya marichamy
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingabhay singh
 
operator overloading
operator overloadingoperator overloading
operator overloadingNishant Joshi
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++Danial Mirza
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++Ilio Catallo
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVAMuskanSony
 

Was ist angesagt? (19)

Lecture5
Lecture5Lecture5
Lecture5
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
 
pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphism
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Compile time polymorphism
Compile time polymorphismCompile time polymorphism
Compile time polymorphism
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 

Andere mochten auch

Review on Bovine Cysticercosis and its Public health importance in Ethiopia ...
Review on Bovine Cysticercosis and its Public health importance in Ethiopia  ...Review on Bovine Cysticercosis and its Public health importance in Ethiopia  ...
Review on Bovine Cysticercosis and its Public health importance in Ethiopia ...Kassahun Semie
 

Andere mochten auch (8)

java concept
java conceptjava concept
java concept
 
Characteristics of oop
Characteristics of oopCharacteristics of oop
Characteristics of oop
 
Review on Bovine Cysticercosis and its Public health importance in Ethiopia ...
Review on Bovine Cysticercosis and its Public health importance in Ethiopia  ...Review on Bovine Cysticercosis and its Public health importance in Ethiopia  ...
Review on Bovine Cysticercosis and its Public health importance in Ethiopia ...
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
polymorphism
polymorphism polymorphism
polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Ähnlich wie 2CPP10 - Polymorphism

11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptxAtharvPotdar2
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method OverridingMichael Heron
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator OverloadingMichael Heron
 
Presentation on polymorphism in c++.pptx
Presentation on polymorphism in c++.pptxPresentation on polymorphism in c++.pptx
Presentation on polymorphism in c++.pptxvishwadeep15
 
Object Oriented programming Using Python.pdf
Object Oriented programming Using Python.pdfObject Oriented programming Using Python.pdf
Object Oriented programming Using Python.pdfRishuRaj953240
 
9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdfanaveenkumar4
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
polymorphism.pdf
polymorphism.pdfpolymorphism.pdf
polymorphism.pdfriyawagh2
 
implementing oop_concept
 implementing oop_concept implementing oop_concept
implementing oop_conceptAmit Gupta
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiMuhammed Thanveer M
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionSamuelAnsong6
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Comparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphismComparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphismCHAITALIUKE1
 
Object Oriented Programming.pptx
 Object Oriented Programming.pptx Object Oriented Programming.pptx
Object Oriented Programming.pptxShuvrojitMajumder
 

Ähnlich wie 2CPP10 - Polymorphism (20)

11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method Overriding
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
oops.pptx
oops.pptxoops.pptx
oops.pptx
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
 
Presentation on polymorphism in c++.pptx
Presentation on polymorphism in c++.pptxPresentation on polymorphism in c++.pptx
Presentation on polymorphism in c++.pptx
 
Object Oriented programming Using Python.pdf
Object Oriented programming Using Python.pdfObject Oriented programming Using Python.pdf
Object Oriented programming Using Python.pdf
 
9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
polymorphism.pdf
polymorphism.pdfpolymorphism.pdf
polymorphism.pdf
 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)
 
implementing oop_concept
 implementing oop_concept implementing oop_concept
implementing oop_concept
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) Introduction
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Comparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphismComparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphism
 
C++ first s lide
C++ first s lideC++ first s lide
C++ first s lide
 
Object Oriented Programming.pptx
 Object Oriented Programming.pptx Object Oriented Programming.pptx
Object Oriented Programming.pptx
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Lecture # 02 - OOP with Python Language by Muhammad Haroon
Lecture # 02 - OOP with Python Language by Muhammad HaroonLecture # 02 - OOP with Python Language by Muhammad Haroon
Lecture # 02 - OOP with Python Language by Muhammad Haroon
 

Mehr von Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael Heron
 

Mehr von Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 

Kürzlich hochgeladen

OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfkalichargn70th171
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 

Kürzlich hochgeladen (20)

OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 

2CPP10 - Polymorphism

  • 2. Introduction • The last of the three fundamental pillars of object orientation is the principle of polymorphism. • It’s also the most abstract and difficult to initially see the benefits of. • In the C++ model of polymorphism, it is inextricably tied up in the idea of inheritance. • They go together, hand in hand.
  • 3. Polymorphism • The word Polymorphism comes from the Greek. • Poly meaning ‘parrot’ • Morph meaning ‘small man made of plasticine’. • In basic terms, it means: • To treat a specialised object as an instance of its more general case. • For example, a Circle is a Circle. • But in a more general way, it’s also a shape.
  • 4. The Scenario • We’re going to explore the topic of polymorphism through a simple example program. • It relates to the relationship between two classes – an Employee and a Manager. • They are very similar except: • Managers can hire and fire • Employees cannot.
  • 5. The Employee Class class Employee { private: int payscale; public: int query_payscale(); void set_payscale (int p); bool can_hire_and_fire(); }; #include "Employee.h" bool Employee::can_hire_and_fire(){ return false; } void Employee::set_payscale(int val) { payscale = val; } int Employee::query_payscale() { return payscale; }
  • 6. The Manager Class class Manager : public Employee { public: bool can_hire_and_fire(); }; #include "Manager.h" bool Manager::can_hire_and_fire() { return true; }
  • 7. The Program #include <iostream> #include "Employee.h" #include "Manager.h" using namespace std; int main(int argc, char** argv) { Employee *emp = new Employee(); Manager *man = new Manager(); cout << "Employees hiring and firing rights:" << emp- >can_hire_and_fire() << endl; cout << "Managerss hiring and firing rights:" << man- >can_hire_and_fire() << endl; return 1 }
  • 8. The Output • So far, it’s pretty straightforward. • Output for employees is 0. • False • Output for managers is 1. • True. • So it is written, so shall it be. • The polymorphism comes in when when we want to do something a little more arcane. • Make a pointer to a base class point to am object of a more specialised class.
  • 9. Polymorphism #include <iostream> #include "Employee.h" #include "Manager.h" using namespace std; int main(int argc, char** argv) { Employee *emp = new Employee(); Manager *man = new Manager(); Employee *poly = new Manager(); cout << "Employees hiring and firing rights:" << emp->can_hire_and_fire() << endl; cout << "Managers hiring and firing rights:" << man->can_hire_and_fire() << endl; cout << "Polymorphic hiring and firing rights:" << poly- >can_hire_and_fire() << endl; return 1; }
  • 10. And…? • What happens now? • In Java, it calls the most specialised version of the method. • It would call the one defined in Manager. • In C++, it calls the method as defined in the class that is referenced by the pointer. • It would call the one defined in Employee. • Okay, great – but so what?
  • 11. The Power • The power comes from when we have many different classes that extend from a common core. • Rather than coding special conditions for each of them, we code for the base class. • This greatly reduces the amount of work that a developer has to do. • And properly distributes the responsibility for implementing functionality.
  • 12. Virtual Functions • However, much of this is based on the idea that we can trust a generalised reference to execute the most appropriate method. • As is done in Java • C++ requires us to define a function as virtual if we want this behaviour. • From this point on, it becomes a virtual function and behaves in the way we would expect from Java.
  • 13. Modified Class Definition class Employee { private: int payscale; public: int query_payscale(); void set_payscale (int p); virtual bool can_hire_and_fire(); };
  • 14. How Do Virtuals Work? • When an object is created from a class, C++ creates a lookup table for virtual functions. • This is in addition to all other data stored. • Each virtual function has an entry in this table. • When you create the object with new, the entry is updated with a reference to the appropriately specialized implementation. • Each virtual method you declare increases the size of this table. • And thus size of the objects and processing time.
  • 15. Clerical Staff #include "Employee.h" class Clerical: public Employee { public: bool can_hire_and_fire(); void file_papers(); }; #include "Clerical.h" bool Clerical::can_hire_and_fire() { return false; } void Clerical::file_papers() { // Something Something }
  • 16. Modified Scenario • Two classes stem from the same root. • Employee • Using the Power of Polymorphism, we can treat them as instances of the base class. • We can manipulate them as if they were just Employees. • This means that we can’t make use of methods defined in the specialised classes. • Only what we can guarantee is implemented by virtue of the class hierarchy.
  • 17. New Code using namespace std; void set_payscale (Employee* emp, float amount) { emp->set_payscale (amount); } int main(int argc, char** argv) { Employee *emp = new Employee(); Manager *man = new Manager(); Clerical *cler = new Clerical(); cout << "Employees hiring and firing rights:" << emp->can_hire_and_fire() << endl; cout << "Managers hiring and firing rights:" << man->can_hire_and_fire() << endl; cout << "Clerical hiring and firing rights:" << cler->can_hire_and_fire() << endl; set_payscale (cler, 15000.0); set_payscale (man, 25000.0); cout << "Clerical payscale: " << cler->query_payscale() << endl; cout << "Manager payscale: " << man->query_payscale() << endl; return 1; }
  • 18. The Employee Class • The Employee class is now something we don’t really want people using it. • It’s a common core, not a fully fledged object in its own right. • In the next lecture, we’ll look at how we can prevent people making use of it directly. • We’ll also look at ways other than inheritance to provide a structure for objects.
  • 19. Benefits of Polymorphism • One of the benefits that comes from polymorphism is the ease of processing lists of objects. • We don’t need a separate queue for Managers and Clerical staff • We just need one queue of employees • We can iterate over each of these, provided we are making use of base functions.
  • 20. Benefits of Polymorphism using namespace std; void set_payscale (Employee* emp, float amount) { emp->set_payscale (amount); } int main(int argc, char** argv) { Employee *emp = new Employee(); Employee **emps = new Employee*[2]; emps[0] = new Manager(); emps[1] = new Clerical(); for (int i = 0; i < 2; i++) { set_payscale (emps[i], 20000.0); cout << "Payscale for " << i << " is " << emps[i]->query_payscale() << endl; } return 1; }
  • 21. Benefits of Polymorphism • Polymorphism manages the complexity of the inheritance model and lets you provide custom handling in the classes themselves. • You don’t need: • if (it’s a manager) { do_this(); } else if (it’s a clerical) { do_this_other_thing() } • One method, properly designed, can handle all the heavy lifting. • This does require the use of a clean, well designed object hierarchy.
  • 22. Summary • Polymorphism is the last of the three pillars of object oriented programming. • The most powerful, but also the most abstract. • You’re not really expected to ‘get it’ just yet. • We’ll return to the topic in later lectures. • In the next lecture we’re going to continue discussing some of the ways in which we can enforce structure on our unruly objects.