SlideShare a Scribd company logo
1 of 30
CMSC 202
Polymorphism
2
Inheritance and Polymorphism
• Inheritance allows us to define a family of classes
that share a common interface.
• Polymorphism allows us to manipulate objects of
these classes in a type-independent way.
• We program the common interface through a
pointer or reference to an (abstract) base class. The
actual operation to invoke is not determined until
run-time based on the specific type of object
actually addressed.
3
C++ and Polymorphism
• Polymorphism is the ability of a base class
pointer (or reference) to refer transparently
to any of its derived classes.
• Polymorphism (and dynamic binding) are
supported only when we use pointers (or
references)
4
Inheritance and Pointers
• A base class pointer can point to an object of a
derived class
– Derived class object “is-a” base class object
– But can’t use pointer to call methods only defined in the
derived class.
• A derived class pointer CANNOT point to the
base class
– The base class doesn’t have any of the extensions
provided by the derived class
5
Static vs. Dynamic Binding
• Binding
The determination of which method in the class
hierarchy is to be invoked for a particular object.
• Static (Early) Binding occurs at compile time
When the compiler can determine which method in the
class hierarchy to use for a particular object.
• Dynamic (Late) Binding occurs at run time
When the determination of which method in the class
hierarchy to use for a particular object occurs during
program execution.
6
Static Binding
For example,
Time t1;
ExtTime et2;
t1.setTime(12, 30, 00); // static binding
et1.setExtTime(13, 45, 30); // static binding
t1.printTime( ); // static binding – Time’s printTime( )
et1.printTime(); // static binding – ExtTime’s printTime( )
7
Dynamic Binding
• Compiler cannot determine binding of object to
method
• Binding is determined dynamically at runtime
• To indicate that a method is to be bound dynamically,
the base class must use the reserved word virtual
• When a method is defined as virtual, all overriding
methods from that point on down the hierarchy are
virtual, even if not explicitly defined to be so
8
A common example
class Shape {
public:
virtual void draw ( ) const = 0; // pure virtual
virtual void error ( ); // virtual
void objectID ( ); // non virtual
};
void Shape::error ( )
{
cerr << “Shape error” << endl;
}
void objectID ( )
{
cout << “a shape” << endl;
}
9
class Circle : public Shape
{
public:
virtual void draw( ) const; // method for drawing a circle
virtual void error ( ); // overriding Shape::error
…
};
void Circle::draw ( ) const
{
// code for drawing a circle
}
void Circle::error ( )
{
cout << “Circle error” << endl;
}
10
class Rectangle : public Shape
{
public:
virtual void draw( ) const; // method for drawing a rectangle
…
};
void Rectangle::draw ( ) const
{
// code to draw a rectangle
}
11
Now consider these pointers:
Shape *pShape;
Circle *pCircle = new Circle;
Rectangle *pRectangle = new Rectangle;
Each pointer has static type based on the way it’s defined in the
program text.
The pointer’s dynamic type is determined by the type of object to
which they currently refer.
pShape = pCircle; // pShape’s dynamic type is now Circle
pShape->draw( ); // calls Circle::draw and draws a circle
pShape = pRectangle; // pShape’s dynamic type is Rectangle
pShape->draw ( ); // calls Rectangle::draw
12
An array of base class pointers
Shape *shapes[3];
shapes[0] = new Circle;
shapes[1] = new Rectangle;
shapes[2] = new Triangle;
for (int s = 0; s < 3; s++)
shapes[s]->draw( );
13
A linked list of base class
pointers
LinkedList<Shape * > shapes;
shapes.insert (new Circle);
shapes.insert (new Rectangle);
shapes.insert (new Triangle);
// traverse the list, printing each Shape in list
14
DOG WHALE
CAT
ANIMAL
A simple ANIMAL hierarchy
15
class Animal {
public:
Animal ( ) {name = “no name”, nrLegs = 0;}
Animal ( string s, int L) : name (s), nrLegs(L) { }
virtual ~Animal ( );
virtual void speak ( ) const { cout << “Hi, Bob”; }
string getName (void) const { return name; }
void setName (string s) { name = s; }
void setNrLegs (int legs) { nrLegs = legs;}
int getNrLegs ( void ) const { return nrLegs;}
private:
string name;
int nrLegs;
};
16
class Dog : public Animal
{
public:
Dog ( ) : Animal (“dog”, 4), breed (“dog”) { }
Dog (string s1, strings2) : Animal (s1, 4), breed (s2) { }
~Dog ( );
void setBreed (string s1) { breed = s1; }
string getBreed (void ) const { return breed;}
void speak ( ) const
{ cout << “Bow Wow ”; }
void speak (int n) const
{ for (int j = 0; j < n: j++) speak ( ); }
. . . . . .
private:
string breed;
};
17
class Whale : public Animal
{
public:
Whale ( );
~Whale ( );
private:
};
18
main ( ) {
Animal anAnimal (“Homer”, 2);
Dog aDog (“Fido”, “mixed”);
Whale aWhale (“Orka”);
anAnimal.speak( );
aDog.speak( );
aDog.speak( 4 );
aWhale.speak( ) ;
Animal *zoo[ 3 ];
zoo[0] = new Whale;
zoo[1] = new Animal;
zoo[2] = new Dog (“Max”, “Terrier”);
for (int a = 0; a < 3; a++) {
cout << zoo[a]->getName( ) << “ says: “
zoo[a] -> speak( );
}
}
19
Works for functions too
• Perhaps the most important use of polymorphism
is the writing of functions to deal with all classes
in the inheritance hierarchy. This is accomplished
by defining the function parameters as pointers (or
references) to base class objects, then having the
caller pass in a pointer (or reference) to a derived
class object. Dynamic binding calls the
appropriate method.
• These functions are often referred to as
“polymorphic” functions.
20
drawShape( ) with a pointer
void drawShape ( Shape *sp)
{
cout << “I am “ ;
sp -> objectID ( );
sp -> draw ( );
if (something bad)
sp->error ( );
}
What is the output if drawShape( ) is passed
a pointer to a Circle?
a pointer to a Rectangle?
21
drawShape ( ) via reference
void drawShape ( Shape& shape)
{
cout << “I am “ ;
shape.objectID ( );
shape.draw ( );
if (something bad)
shape.error ( );
}
What is the output if drawShape is passed
a reference to a Circle?
a reference to a Rectangle?
22
Calling virtual methods from
within other methods
• Suppose virtual drawMe( ) is added to
Shape and inherited by Rectangle without
being overridden.
void Shape::drawMe ( void)
{
cout << “drawing: “ << endl;
draw( );
}
23
Which draw( ) gets called
From within drawMe( ) with this code?
Rectangle r1;
r1.drawMe ( );
The Rectangle version of draw( ), even though
drawMe( ) was only defined in Shape. Why?
Because inside of drawMe( ), the call to draw( ) is
really this->draw ( ); and since a pointer is used,
we get the desired polymorphic behavior.
24
Don’t redefine objectID( )
Note that neither Circle nor Rectangle redefined the objectID( )
method which was a nonvirtual function. But what if they had?
Suppose the Rectangle class had it’s own version of objectID().
Consider this code:
Rectangle R; // a Rectangle object
Shape *pS = &R; // base class pointer to a Rectangle
Rectangle *pR = &R; // derived class pointer to a Rectangle
what is the output of the following?
pS -> objectID ( );
pR -> objectID ( );
Bottom Line – don’t override nonvirtual functions
25
Old code and new code
• In the procedural world (like that of C), it’s easy
for new code to call old code using functions.
However, it’s difficult for old code to call new
code unless it’s modified to know about the new
code.
• In the OO world, old code (polymorphic
functions) can dynamically bind to new code.
This occurs when a new derived class is passed
(by pointer or reference) to the polymorphic
function. The polymorphic function needs no
modification.
26
Don’t Pass by Value
A function which has a base class parameter passed
by value should only be used with base class
objects – for two reasons
1. The function isn’t polymorphic. Polymorphism
only occurs with parameters passed by pointer or
reference
2. Even though a derived class object can be
passed to such a function (a D is-a B), none of
the derived class methods or data members can
be used in that function. This is a phenomenon
called “member slicing”.
27
The same is true for assignment
Time t(10, 5, 0);
ExtTime et(20, 15, 10, ExtTime::EST);
• A derived class object can be assigned to a base class
object
t = et; // legal, BUT Member slicing occurs.
• A base class object cannot be assigned to a derived class
object
et = t; // illegal! Not all data members can be filled
28
Polymorphism and Destructors
• A problem – if an object (with a non-virtual
destructor) is explicitly destroyed by applying the
delete operator to a base class pointer, the base
class destructor is invoked.
Circle C;
Shape *sp = &C;
delete sp; // calls Shape’s destructor
// if the destructor is not
// virtual
• So what ??
29
Polymorphism and Destructors
• Solution -- Declare a virtual destructor for
any base class with at least one virtual
function.
• Then, when the derived class’s destructor is
invoked, the base class destructor will also
be invoked automatically
30
Designing A Base Class with
Inheritance and Polymorphism
in mind
For the base class
1. Identify the set of operations common to all
the children
2. Identify which operations are type-
independent (these become (pure) virtual to
be overridden in derived classes)
3. Identify the access level (public, private,
protected) of each operation
For a more complete discussion, see “Essential C++”, Stanley Lippman (section 5.4)

More Related Content

Similar to this is the concept in C++ under object oriented programming language "POLYMORPHISM"

Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)Durga Devi
 
Virtual function
Virtual functionVirtual function
Virtual functionzindadili
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
Dotnet unit 4
Dotnet unit 4Dotnet unit 4
Dotnet unit 4007laksh
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classDeepak Singh
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaSandesh Sharma
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfrajaratna4
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfbreaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfVishalKumarJha10
 
Core java concepts
Core java concepts Core java concepts
Core java concepts javeed_mhd
 

Similar to this is the concept in C++ under object oriented programming language "POLYMORPHISM" (20)

Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
 
Virtual function
Virtual functionVirtual function
Virtual function
 
L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
Dotnet unit 4
Dotnet unit 4Dotnet unit 4
Dotnet unit 4
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdf
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfbreaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Core java
Core javaCore java
Core java
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
Java Concepts
Java ConceptsJava Concepts
Java Concepts
 

Recently uploaded

How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfFIDO Alliance
 
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties ReimaginedEasier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties Reimaginedpanagenda
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfFIDO Alliance
 
Your enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jYour enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jNeo4j
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...FIDO Alliance
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Skynet Technologies
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch TuesdayIvanti
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfFIDO Alliance
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...FIDO Alliance
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
Oauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftOauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftshyamraj55
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxFIDO Alliance
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...ScyllaDB
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxFIDO Alliance
 

Recently uploaded (20)

How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties ReimaginedEasier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Your enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jYour enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4j
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Oauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftOauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoft
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 

this is the concept in C++ under object oriented programming language "POLYMORPHISM"

  • 2. 2 Inheritance and Polymorphism • Inheritance allows us to define a family of classes that share a common interface. • Polymorphism allows us to manipulate objects of these classes in a type-independent way. • We program the common interface through a pointer or reference to an (abstract) base class. The actual operation to invoke is not determined until run-time based on the specific type of object actually addressed.
  • 3. 3 C++ and Polymorphism • Polymorphism is the ability of a base class pointer (or reference) to refer transparently to any of its derived classes. • Polymorphism (and dynamic binding) are supported only when we use pointers (or references)
  • 4. 4 Inheritance and Pointers • A base class pointer can point to an object of a derived class – Derived class object “is-a” base class object – But can’t use pointer to call methods only defined in the derived class. • A derived class pointer CANNOT point to the base class – The base class doesn’t have any of the extensions provided by the derived class
  • 5. 5 Static vs. Dynamic Binding • Binding The determination of which method in the class hierarchy is to be invoked for a particular object. • Static (Early) Binding occurs at compile time When the compiler can determine which method in the class hierarchy to use for a particular object. • Dynamic (Late) Binding occurs at run time When the determination of which method in the class hierarchy to use for a particular object occurs during program execution.
  • 6. 6 Static Binding For example, Time t1; ExtTime et2; t1.setTime(12, 30, 00); // static binding et1.setExtTime(13, 45, 30); // static binding t1.printTime( ); // static binding – Time’s printTime( ) et1.printTime(); // static binding – ExtTime’s printTime( )
  • 7. 7 Dynamic Binding • Compiler cannot determine binding of object to method • Binding is determined dynamically at runtime • To indicate that a method is to be bound dynamically, the base class must use the reserved word virtual • When a method is defined as virtual, all overriding methods from that point on down the hierarchy are virtual, even if not explicitly defined to be so
  • 8. 8 A common example class Shape { public: virtual void draw ( ) const = 0; // pure virtual virtual void error ( ); // virtual void objectID ( ); // non virtual }; void Shape::error ( ) { cerr << “Shape error” << endl; } void objectID ( ) { cout << “a shape” << endl; }
  • 9. 9 class Circle : public Shape { public: virtual void draw( ) const; // method for drawing a circle virtual void error ( ); // overriding Shape::error … }; void Circle::draw ( ) const { // code for drawing a circle } void Circle::error ( ) { cout << “Circle error” << endl; }
  • 10. 10 class Rectangle : public Shape { public: virtual void draw( ) const; // method for drawing a rectangle … }; void Rectangle::draw ( ) const { // code to draw a rectangle }
  • 11. 11 Now consider these pointers: Shape *pShape; Circle *pCircle = new Circle; Rectangle *pRectangle = new Rectangle; Each pointer has static type based on the way it’s defined in the program text. The pointer’s dynamic type is determined by the type of object to which they currently refer. pShape = pCircle; // pShape’s dynamic type is now Circle pShape->draw( ); // calls Circle::draw and draws a circle pShape = pRectangle; // pShape’s dynamic type is Rectangle pShape->draw ( ); // calls Rectangle::draw
  • 12. 12 An array of base class pointers Shape *shapes[3]; shapes[0] = new Circle; shapes[1] = new Rectangle; shapes[2] = new Triangle; for (int s = 0; s < 3; s++) shapes[s]->draw( );
  • 13. 13 A linked list of base class pointers LinkedList<Shape * > shapes; shapes.insert (new Circle); shapes.insert (new Rectangle); shapes.insert (new Triangle); // traverse the list, printing each Shape in list
  • 15. 15 class Animal { public: Animal ( ) {name = “no name”, nrLegs = 0;} Animal ( string s, int L) : name (s), nrLegs(L) { } virtual ~Animal ( ); virtual void speak ( ) const { cout << “Hi, Bob”; } string getName (void) const { return name; } void setName (string s) { name = s; } void setNrLegs (int legs) { nrLegs = legs;} int getNrLegs ( void ) const { return nrLegs;} private: string name; int nrLegs; };
  • 16. 16 class Dog : public Animal { public: Dog ( ) : Animal (“dog”, 4), breed (“dog”) { } Dog (string s1, strings2) : Animal (s1, 4), breed (s2) { } ~Dog ( ); void setBreed (string s1) { breed = s1; } string getBreed (void ) const { return breed;} void speak ( ) const { cout << “Bow Wow ”; } void speak (int n) const { for (int j = 0; j < n: j++) speak ( ); } . . . . . . private: string breed; };
  • 17. 17 class Whale : public Animal { public: Whale ( ); ~Whale ( ); private: };
  • 18. 18 main ( ) { Animal anAnimal (“Homer”, 2); Dog aDog (“Fido”, “mixed”); Whale aWhale (“Orka”); anAnimal.speak( ); aDog.speak( ); aDog.speak( 4 ); aWhale.speak( ) ; Animal *zoo[ 3 ]; zoo[0] = new Whale; zoo[1] = new Animal; zoo[2] = new Dog (“Max”, “Terrier”); for (int a = 0; a < 3; a++) { cout << zoo[a]->getName( ) << “ says: “ zoo[a] -> speak( ); } }
  • 19. 19 Works for functions too • Perhaps the most important use of polymorphism is the writing of functions to deal with all classes in the inheritance hierarchy. This is accomplished by defining the function parameters as pointers (or references) to base class objects, then having the caller pass in a pointer (or reference) to a derived class object. Dynamic binding calls the appropriate method. • These functions are often referred to as “polymorphic” functions.
  • 20. 20 drawShape( ) with a pointer void drawShape ( Shape *sp) { cout << “I am “ ; sp -> objectID ( ); sp -> draw ( ); if (something bad) sp->error ( ); } What is the output if drawShape( ) is passed a pointer to a Circle? a pointer to a Rectangle?
  • 21. 21 drawShape ( ) via reference void drawShape ( Shape& shape) { cout << “I am “ ; shape.objectID ( ); shape.draw ( ); if (something bad) shape.error ( ); } What is the output if drawShape is passed a reference to a Circle? a reference to a Rectangle?
  • 22. 22 Calling virtual methods from within other methods • Suppose virtual drawMe( ) is added to Shape and inherited by Rectangle without being overridden. void Shape::drawMe ( void) { cout << “drawing: “ << endl; draw( ); }
  • 23. 23 Which draw( ) gets called From within drawMe( ) with this code? Rectangle r1; r1.drawMe ( ); The Rectangle version of draw( ), even though drawMe( ) was only defined in Shape. Why? Because inside of drawMe( ), the call to draw( ) is really this->draw ( ); and since a pointer is used, we get the desired polymorphic behavior.
  • 24. 24 Don’t redefine objectID( ) Note that neither Circle nor Rectangle redefined the objectID( ) method which was a nonvirtual function. But what if they had? Suppose the Rectangle class had it’s own version of objectID(). Consider this code: Rectangle R; // a Rectangle object Shape *pS = &R; // base class pointer to a Rectangle Rectangle *pR = &R; // derived class pointer to a Rectangle what is the output of the following? pS -> objectID ( ); pR -> objectID ( ); Bottom Line – don’t override nonvirtual functions
  • 25. 25 Old code and new code • In the procedural world (like that of C), it’s easy for new code to call old code using functions. However, it’s difficult for old code to call new code unless it’s modified to know about the new code. • In the OO world, old code (polymorphic functions) can dynamically bind to new code. This occurs when a new derived class is passed (by pointer or reference) to the polymorphic function. The polymorphic function needs no modification.
  • 26. 26 Don’t Pass by Value A function which has a base class parameter passed by value should only be used with base class objects – for two reasons 1. The function isn’t polymorphic. Polymorphism only occurs with parameters passed by pointer or reference 2. Even though a derived class object can be passed to such a function (a D is-a B), none of the derived class methods or data members can be used in that function. This is a phenomenon called “member slicing”.
  • 27. 27 The same is true for assignment Time t(10, 5, 0); ExtTime et(20, 15, 10, ExtTime::EST); • A derived class object can be assigned to a base class object t = et; // legal, BUT Member slicing occurs. • A base class object cannot be assigned to a derived class object et = t; // illegal! Not all data members can be filled
  • 28. 28 Polymorphism and Destructors • A problem – if an object (with a non-virtual destructor) is explicitly destroyed by applying the delete operator to a base class pointer, the base class destructor is invoked. Circle C; Shape *sp = &C; delete sp; // calls Shape’s destructor // if the destructor is not // virtual • So what ??
  • 29. 29 Polymorphism and Destructors • Solution -- Declare a virtual destructor for any base class with at least one virtual function. • Then, when the derived class’s destructor is invoked, the base class destructor will also be invoked automatically
  • 30. 30 Designing A Base Class with Inheritance and Polymorphism in mind For the base class 1. Identify the set of operations common to all the children 2. Identify which operations are type- independent (these become (pure) virtual to be overridden in derived classes) 3. Identify the access level (public, private, protected) of each operation For a more complete discussion, see “Essential C++”, Stanley Lippman (section 5.4)