Virtual Functions and Polymorphism
Virtual Functions and Polymorphism
1 11/23/2019
OUTLINE
Polymorphism
Virtual Functions
2 11/23/2019
Polymorphism
The word polymorphism means having many forms.
5 11/23/2019
The Virtual Attribute is Inherited
When a virtual function is inherited, its virtual nature is also
inherited.
No matter how many times a virtual function is inherited, it
remains virtual.
Example3.cpp
6 11/23/2019
Virtual Functions are Hierarchical
When a function is declared as virtual by a base class, it may be
overridden by a derived class. However, the function does not have
to be overridden.
When a derived class fails to override a virtual function, then when
an object of that derived class accesses that function, the function
defined by the base class is used.
Example4.cpp
7 11/23/2019
Pure Virtual Functions
A pure virtual function is a virtual function that has no definition
within the base class.
To declare a pure virtual function, use this general form:
virtual type func_name(parameter-list) = 0;
When a virtual function is made pure, any derived class must provide its
own definition. If the derived class fails to override the pure virtual
function, a compile-time error will result.
Example5.cpp
8 11/23/2019
Abstract Classes
A class that contains at least one pure virtual function is said to be
abstract.
Because an abstract class contains one or more functions for which
there is no definition (that is, a pure virtual function), no objects of
an abstract class may be created.
Although you cannot create objects of an abstract class, you can
create pointers and references to an abstract class.
This allows abstract classes to support run-time polymorphism,
which relies upon base-class pointers and references to select the
proper virtual function.
9 11/23/2019
Early vs. Late Binding
Early Binding Late Binding
Early binding refers to events that occur at Late binding refers to events that occur at
compile time. run time.
Early binding occurs when all information Late binding refers to function calls that
needed to call a function is known at are not resolved until run time.
compile time.
Examples: normal function calls, Examples: Virtual functions
overloaded function calls, and overloaded
operators.
The main advantage to early binding is The main advantage to late binding is
efficiency. flexibility.
These types of function calls are very fast. Late binding can make for somewhat
slower execution times.
10 11/23/2019
11 11/23/2019