13 Polymorphism
13 Polymorphism
• We have two derived classes, Circle and Square, which inherit from the Shape base class. Each
derived class overrides the draw() function to provide its own implementation.
• In the main() function, we create two pointers of type Shape*, shape1 and shape2. We assign a
Circle object to shape1 and a Square object to shape2. Even though the pointers are of type
Shape*, they can hold objects of different derived classes because of polymorphism.
• When we call the draw() function on shape1 and shape2, the appropriate version of the function
is called based on the actual type of the object being referred to at runtime. This is called dynamic
binding or late binding. The draw() function in each derived class is invoked, and the
corresponding message is printed.
Polymorphism Importance
• Polymorphism allows us to write generic code that can
handle different types of shapes without knowing the
specific derived class at compile time.
• It enables code reuse, extensibility, and flexibility in
object-oriented systems.
Pure virtual functions
• Pure virtual functions, also known as abstract functions, are virtual
functions in the base class that have no implementation.
• They are declared with the virtual keyword and assigned a value of 0
using the = 0 syntax.
• Pure virtual functions act as placeholders for functions that must be
implemented in the derived classes.
Abstract Class
• An abstract class is a class that is designed to be a base
class for other classes but cannot be instantiated on its
own. It typically contains at least one pure virtual
function, making it an abstract base class. An abstract
class provides a common interface or contract that
derived classes must implement.
Explanation
In this example, the Shape class is an
abstract class with a pure virtual function
draw(). This means that any class derived
from Shape must implement the draw()
function. The Circle and Rectangle classes
inherit from Shape and provide their own
implementations of the draw() function.