Lesson Introduction

Polymorphism is a key concept in C++ that allows objects from different classes to be treated as objects of a shared base class. It makes your code more flexible and reusable. The term "polymorphism" stems from Greek words meaning "many forms."

Our goal in this lesson is to understand the basics of polymorphism in C++ by working with a chess example.

What is Polymorphism and Why Do We Need It?

Polymorphism allows you to design and implement programs that are more flexible and easier to extend over time. It enables one interface to be used for a general class of actions, with specific actions determined by the exact nature of the situation.

In C++, polymorphism is primarily achieved through the use of base class pointers or references to invoke methods in derived classes. This makes it possible to write code that can work with objects of different types and classes in a unified way. Sounds difficult? It really isn't! Let's see an example, it will help you understand the idea.

Define an Abstract Class: `ChessPiece`

An abstract class in C++ is a class that cannot be instantiated on its own and is designed to be inherited by other classes. It serves as a blueprint for derived classes. An abstract class typically includes one or more pure virtual functions.

A pure virtual function is a function declaration that is specified in the base class but has no implementation in that class. Instead, it must be implemented by any non-abstract derived class. This is done by assigning 0 to the function declaration in the base class.

Additionally, it's a good practice to have a virtual destructor in an abstract class. This ensures that the destructor for derived classes will be called correctly, preventing memory leaks.

We'll define an abstract class ChessPiece with a pure virtual function and a virtual destructor. This function will be overridden by derived classes.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal