Lect04 CPP Polymorphism
Lect04 CPP Polymorphism
2022
Contents
1. Basics of Polymorphism
2. Diamond Problem
4. Workshop
Basics of Polymorphism
Object Reference and Object Pointer
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
Workshop
Director Director* p
4
Object Pointer and Assignment
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
Workshop
Human Director
Human* p Director* q
p q
assignment?
5
Polymorphism
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
Concept 1 (General)
Workshop
“Poly” is Greek for many, and “morph” means form. Polymorphism is that
feature of object-oriented languages that allows objects of different types to be
treated similarly.
Concept 2 (C++)
Polymorphism allows an object reference variable or an object pointer to
reference objects of different types and to call the correct member functions,
depending upon the type of object being referenced.
6
Polymorphism (cont.)
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
Workshop
Quack
Woof
Speak Class Animal
Moew
7
Need for Polymorphic Behavior
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? • It is possible that both Tuna and Carp provide their own Tuna::Swim() and
Workshop Carp::Swim() methods to make Tuna and Carp different swimmers.
• If a user with an instance of Tuna uses the base class type to invoke
Fish::Swim(), he ends up executing only the generic part Fish::Swim()
and not Tuna::Swim(), even though that base class instance Fish is a part
of a Tuna.
8
Listing 1
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
#include <iostream > void MakeFishSwim(Fish& InputFish) {
Workshop
using namespace std; // calling Fish :: Swim
class Fish { InputFish.Swim ();
public: }
void Swim () { int main () {
cout << "Fish swims!" << endl; Tuna myDinner;
} // calling Tuna :: Swim
}; myDinner.Swim ();
class Tuna:public Fish { // sending Tuna as Fish
public: MakeFishSwim(myDinner);
// override Fish :: Swim return 0;
void Swim () { }
cout << "Tuna swims!" << endl;
}
};
9
Polymorphic Behavior Implemented Using Virtual
Basics of
Polymorphism
Diamond
Problem Functions
Virtual Copy
Constructors?
Workshop
Concept 3
The virtual function provides the ability to define a function in a base class and
have a function of the same name and type in a derived class called when a user
calls the base class function.
Syntax
class Base {
virtual ReturnType FunctionName (Parameter List);
};
class Derived : public Base {
ReturnType FunctionName (Parameter List);
};
10
UML
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
Workshop Name
attribute1
attribute2 italic style means virtual
operation1()
operation2()
11
Listing 2
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
#include <iostream > class Carp:public Fish {
Workshop
using namespace std; public:
class Fish { // override Fish :: Swim
public: void Swim () {
virtual void Swim () { cout << "Carp swims!" << endl;
cout << "Fish swims!" << endl; }
} };
}; void MakeFishSwim(Fish& InputFish) {
class Tuna:public Fish { // calling virtual method Swim ()
public: InputFish.Swim ();
// override Fish :: Swim }
void Swim () { int main () {
cout << "Tuna swims!" << endl; Tuna myDinner;
} Carp myLunch;
}; // sending Tuna as Fish
MakeFishSwim(myDinner);
// sending Carp as Fish
MakeFishSwim(myLunch);
return 0;
}
12
Need for Virtual Destructors
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? • What happens when a function calls operator delete using a pointer of type
Workshop Base* that actually points to an instance of type Derived?
13
Need for Virtual Destructors (cont.)
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? • To avoid this problem, we use virtual destructors
Workshop
class Fish {
public :
Fish () {
cout << " Constructed Fish" << endl;
}
virtual ~Fish () { // virtual destructor !
cout << " Destroyed Fish" << endl;
}
};
14
Static binding vs Dynamic binding
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? Binding
Workshop • The determination of which method in the class hierarchy is to be used for a
particular object.
Static (Early) Binding
• When the compiler can determine which method in the class hierarchy to use
for a particular object.
Dynamic (Late) Binding
• When the determination of which method in the class hierarchy to use for a
particular object occurs during program execution.
15
How Do virtual Functions Work
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? • Consider a class Base that declared N virtual functions:
Workshop
class Base {
public :
virtual void Func1 () {
// Func1 implementation
}
virtual void Func2 () {
// Func2 implementation
}
// .. so on and so forth
virtual void FuncN () {
// FuncN implementation
}
};
16
How Do virtual Functions Work (cont.)
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
• class Derived that inherits from Base overrides Base::Func2(), exposing
Workshop the other virtual functions directly from class Base:
class Derived : public Base {
public :
virtual void Func1 () {
// Func2 overrides Base :: Func2 ()
}
// no implementation for Func2 ()
virtual void FuncN () {
// FuncN implementation
}
};
17
How Do virtual Functions Work (cont.)
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? The compiler sees an inheritance hierarchy and understands that the Base defines
Workshop certain virtual functions that have been overridden in Derived. What the
compiler now does is to create a table called the Virtual Function Table (VFT)
for every class that implements a virtual function or derived class that overrides it.
18
How Do virtual Functions Work (cont.)
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? • Each table is comprised of function pointers, each pointing to the available
Workshop implementation of a virtual function
void DoSomething (Base& objBase ) {
objBase .Func1 (); // invoke Derived :: Func1
}
int main ()
{
Derived objDerived ;
objDerived .Func2 ();
DoSomething ( objDerived );
};
19
Abstract Base Classes and Pure Virtual Functions
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? Concept 4
Workshop
Syntax
class AbstractBase {
public:
virtual void DoSomething() = 0; // pure virtual method
};
20
Object-Oriented Design
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
• Sometimes it is helpful to begin a class hierarchy with an abstract base class.
Workshop The abstract base class represents the generic, or abstract, form of all the
classes that are derived from it.
Principle
“High-level modules should not depend upon low-level modules. Both
should depend upon abstractions.”
“Abstractions should not depend on details. Details should depend on
abstractions.”
21
UML
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
Workshop Name
22
Listing 3
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
#include <iostream > class Carp:public Fish {
Workshop
using namespace std; void Swim () {
class Fish { cout << "Carp swims" << endl;
public: }
// a pure virtual function Swim };
virtual void Swim () = 0; void MakeFishSwim(Fish& inputFish) {
}; inputFish.Swim ();
class Tuna:public Fish { }
public: int main () {
void Swim () { // Fish myFish; // Fails
cout << "Tuna swims" << endl; Carp myLunch;
} Tuna myDinner;
}; MakeFishSwim(myLunch);
MakeFishSwim(myDinner);
return 0;
}
23
Diamond Problem
Diamond Problem
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? Replicated based class
Workshop • With the ability of specifying more than one base class, there may be a
chance of having the same base class more than once.
Diamond problem
ClassA
ClassB ClassC
ClassD
25
Diamond Problem (cont.)
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
26
Diamond Problem (cont.)
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
Workshop
Animal Animal Animal
Platypus
27
Lisiting 4
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
#include <iostream > class Platypus:public Mammal , public
Workshop
using namespace std; Bird , public Reptile {
class Animal { public:
public: Platypus () {
Animal () { cout << "Platypus constructor"
cout << "Animal constructor" << << endl;
endl; }
} };
int Age; int main () {
}; Platypus duckBilledP;
class Mammal:public Animal { // Age is ambiguous as there are
}; // three instances of base Animal
class Bird:public Animal { duckBilledP.Age = 25;
}; return 0;
class Reptile:public Animal { }
};
28
Using virtual Inheritance to Solve the Diamond Problem
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? • The solution is in virtual inheritance
Workshop
Syntax
class Derived1: public virtual Base {
// ... members and functions
};
class Derived2: public virtual Base {
// ... members and functions
};
29
Lisiting 5
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors?
#include <iostream > class Platypus:public Mammal , public
Workshop
using namespace std; Bird , public Reptile {
class Animal { public:
public: Platypus () {
Animal () { cout << "Platypus constructor"
cout << "Animal constructor" << << endl;
endl; }
} };
int Age; int main () {
}; Platypus duckBilledP;
class Mammal:public virtual Animal { // no compile error
}; duckBilledP.Age = 25;
class Bird:public virtual Animal { return 0;
}; }
class Reptile:public virtual Animal {
};
30
Virtual Copy Constructors?
Virtual Copy Constructors?
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? • It is technically impossible in C++ to have virtual copy constructors
Workshop
• Virtual copy constructors are not possible because the virtual keyword in
context of base class methods being overridden by implementations available
in the derived class are about polymorphic behavior generated at runtime.
• Constructors, on the other hand, are not polymorphic in nature as they can
construct only a fixed type, and hence C++ does not allow usage of the
virtual copy constructors.
• Design pattern: Propotype Pattern
32
Virtual Clone Method
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? class Fish {
Workshop public :
virtual Fish* Clone () const = 0; // pure virtual function
};
33
Workshop
Quiz
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? 1. What is a virtual method?
Workshop .........................................................................
.........................................................................
.........................................................................
2. When does static binding take place? When does dynamic binding take
place?
.........................................................................
.........................................................................
.........................................................................
3. What is an abstract base class?
.........................................................................
.........................................................................
.........................................................................
35
Exercises
Basics of
Polymorphism
Diamond
Problem
Virtual Copy
Constructors? • Programming Challenges of chapter 15 [Gaddis, 2014]
Workshop 9. File Filter
12. Ship , CruiseShip , and CargoShip Classes
36
References
Deitel, P. (2016).
C++: How to program.
Pearson.
Gaddis, T. (2014).
Starting Out with C++ from Control Structures to Objects.
Addison-Wesley Professional, 8th edition.
Jones, B. (2014).
Sams teach yourself C++ in one hour a day.
Sams.