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.

More Related Content

PPTX
Pointers,virtual functions and polymorphism cpp
PPTX
Polymorphism
PDF
Operator overloading
PPTX
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
PPT
Overloading
PPT
Operator Overloading
PPTX
Operator Overloading
PPT
pointers, virtual functions and polymorphisms in c++ || in cpp
Pointers,virtual functions and polymorphism cpp
Polymorphism
Operator overloading
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Overloading
Operator Overloading
Operator Overloading
pointers, virtual functions and polymorphisms in c++ || in cpp

What's hot (19)

PPT
Lecture5
PPTX
Operator Overloading & Type Conversions
PPTX
Templates in C++
PPTX
Pointers, virtual function and polymorphism
PPT
C++ overloading
PPT
friends functionToshu
PPTX
pointer, virtual function and polymorphism
PPTX
operator overloading & type conversion in cpp over view || c++
PPTX
Compile time polymorphism
PPTX
Operator overloading
PPT
Operator overloading
PPTX
operator overloading
PPTX
Data Type Conversion in C++
PDF
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
PPT
14 operator overloading
PPTX
Unary operator overloading
PDF
Functions in C++
PDF
Operator overloading in C++
PPTX
TEMPLATES IN JAVA
Lecture5
Operator Overloading & Type Conversions
Templates in C++
Pointers, virtual function and polymorphism
C++ overloading
friends functionToshu
pointer, virtual function and polymorphism
operator overloading & type conversion in cpp over view || c++
Compile time polymorphism
Operator overloading
Operator overloading
operator overloading
Data Type Conversion in C++
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
14 operator overloading
Unary operator overloading
Functions in C++
Operator overloading in C++
TEMPLATES IN JAVA
Ad

Viewers also liked (8)

PPSX
java concept
PPTX
Characteristics of oop
PDF
Review on Bovine Cysticercosis and its Public health importance in Ethiopia ...
PDF
Java Inheritance
PPTX
Polymorphism
PPTX
polymorphism
PPTX
Polymorphism
PDF
Polymorphism
java concept
Characteristics of oop
Review on Bovine Cysticercosis and its Public health importance in Ethiopia ...
Java Inheritance
Polymorphism
polymorphism
Polymorphism
Polymorphism
Ad

Similar to 2CPP10 - Polymorphism (20)

PPTX
11.C++Polymorphism [Autosaved].pptx
PPTX
Polymorphism.Difference between Inheritance & Polymorphism
PPTX
2CPP12 - Method Overriding
PPTX
Presentation 4th
PPTX
oops.pptx
PPTX
2CPP13 - Operator Overloading
PPTX
Presentation on polymorphism in c++.pptx
PPTX
Presentation on topic of c and c++ programming language.(.pptx
PDF
9-_Object_Oriented_Programming_Using_Python.pdf
PDF
Object Oriented programming Using Python.pdf
KEY
Exciting JavaScript - Part I
PPTX
9-_Object_Oriented_Programming_Using_Python 1.pptx
PPTX
9-_Object_Oriented_Programming_Using_Python 1.pptx
PDF
polymorphism.pdf
PPTX
OOPS & C++(UNIT 4)
PPT
implementing oop_concept
PPTX
Oop concept in c++ by MUhammed Thanveer Melayi
PPTX
Object Oriented Programming (OOP) Introduction
PPTX
Object Oriented Programming in Python.pptx
PDF
Twins: Object Oriented Programming and Functional Programming
11.C++Polymorphism [Autosaved].pptx
Polymorphism.Difference between Inheritance & Polymorphism
2CPP12 - Method Overriding
Presentation 4th
oops.pptx
2CPP13 - Operator Overloading
Presentation on polymorphism in c++.pptx
Presentation on topic of c and c++ programming language.(.pptx
9-_Object_Oriented_Programming_Using_Python.pdf
Object Oriented programming Using Python.pdf
Exciting JavaScript - Part I
9-_Object_Oriented_Programming_Using_Python 1.pptx
9-_Object_Oriented_Programming_Using_Python 1.pptx
polymorphism.pdf
OOPS & C++(UNIT 4)
implementing oop_concept
Oop concept in c++ by MUhammed Thanveer Melayi
Object Oriented Programming (OOP) Introduction
Object Oriented Programming in Python.pptx
Twins: Object Oriented Programming and Functional Programming

More from Michael Heron (20)

PPTX
Meeple centred design - Board Game Accessibility
PPTX
Musings on misconduct
PDF
Accessibility Support with the ACCESS Framework
PDF
ACCESS: A Technical Framework for Adaptive Accessibility Support
PPTX
Authorship and Autership
PDF
Text parser based interaction
PPTX
SAD04 - Inheritance
PPT
GRPHICS08 - Raytracing and Radiosity
PPT
GRPHICS07 - Textures
PPT
GRPHICS06 - Shading
PPT
GRPHICS05 - Rendering (2)
PPT
GRPHICS04 - Rendering (1)
PPTX
GRPHICS03 - Graphical Representation
PPTX
GRPHICS02 - Creating 3D Graphics
PPTX
GRPHICS01 - Introduction to 3D Graphics
PPT
GRPHICS09 - Art Appreciation
PPTX
2CPP18 - Modifiers
PPTX
2CPP17 - File IO
PPT
2CPP16 - STL
PPT
2CPP15 - Templates
Meeple centred design - Board Game Accessibility
Musings on misconduct
Accessibility Support with the ACCESS Framework
ACCESS: A Technical Framework for Adaptive Accessibility Support
Authorship and Autership
Text parser based interaction
SAD04 - Inheritance
GRPHICS08 - Raytracing and Radiosity
GRPHICS07 - Textures
GRPHICS06 - Shading
GRPHICS05 - Rendering (2)
GRPHICS04 - Rendering (1)
GRPHICS03 - Graphical Representation
GRPHICS02 - Creating 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
GRPHICS09 - Art Appreciation
2CPP18 - Modifiers
2CPP17 - File IO
2CPP16 - STL
2CPP15 - Templates

Recently uploaded (20)

PPTX
Download Adobe Photoshop Crack 2025 Free
PPTX
Full-Stack Developer Courses That Actually Land You Jobs
PDF
CCleaner 6.39.11548 Crack 2025 License Key
PDF
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
PPTX
most interesting chapter in the world ppt
PPTX
CNN LeNet5 Architecture: Neural Networks
PDF
Visual explanation of Dijkstra's Algorithm using Python
PDF
AI Guide for Business Growth - Arna Softech
PPTX
MLforCyber_MLDataSetsandFeatures_Presentation.pptx
PDF
Multiverse AI Review 2025: Access All TOP AI Model-Versions!
PDF
Type Class Derivation in Scala 3 - Jose Luis Pintado Barbero
PPTX
Tech Workshop Escape Room Tech Workshop
PDF
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
PDF
AI/ML Infra Meetup | LLM Agents and Implementation Challenges
PDF
Topaz Photo AI Crack New Download (Latest 2025)
PDF
How Tridens DevSecOps Ensures Compliance, Security, and Agility
PDF
Practical Indispensable Project Management Tips for Delivering Successful Exp...
PDF
Wondershare Recoverit Full Crack New Version (Latest 2025)
PDF
DNT Brochure 2025 – ISV Solutions @ D365
PPTX
GSA Content Generator Crack (2025 Latest)
Download Adobe Photoshop Crack 2025 Free
Full-Stack Developer Courses That Actually Land You Jobs
CCleaner 6.39.11548 Crack 2025 License Key
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
most interesting chapter in the world ppt
CNN LeNet5 Architecture: Neural Networks
Visual explanation of Dijkstra's Algorithm using Python
AI Guide for Business Growth - Arna Softech
MLforCyber_MLDataSetsandFeatures_Presentation.pptx
Multiverse AI Review 2025: Access All TOP AI Model-Versions!
Type Class Derivation in Scala 3 - Jose Luis Pintado Barbero
Tech Workshop Escape Room Tech Workshop
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
AI/ML Infra Meetup | LLM Agents and Implementation Challenges
Topaz Photo AI Crack New Download (Latest 2025)
How Tridens DevSecOps Ensures Compliance, Security, and Agility
Practical Indispensable Project Management Tips for Delivering Successful Exp...
Wondershare Recoverit Full Crack New Version (Latest 2025)
DNT Brochure 2025 – ISV Solutions @ D365
GSA Content Generator Crack (2025 Latest)

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.