What is inheritance and polymorphism in C++?

Table of Contents

Inheritance in C++

Understanding Inheritance
Inheritance is a mechanism in C++ that allows a new class, known as a derived class, to inherit attributes and methods from an existing class, known as a base class. This promotes code reuse and establishes a hierarchical relationship between classes.

Types of Inheritance

  1. Single Inheritance: A derived class inherits from a single base class.
  2. Multiple Inheritance: A derived class inherits from more than one base class.
  3. Multilevel Inheritance: A derived class inherits from another derived class.
  4. Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
  5. Hybrid Inheritance: A combination of two or more types of inheritance.

Example:

Polymorphism in C++

Understanding Polymorphism
Polymorphism allows methods to do different things based on the object’s type that invokes them. It is mainly achieved through method overriding in derived classes and virtual functions in C++.

Types of Polymorphism

  1. Compile-time Polymorphism: Achieved through function overloading and operator overloading.
  2. Run-time Polymorphism: Achieved through method overriding and virtual functions.

Using Virtual Functions
Virtual functions enable a base class to declare methods that can be overridden in derived classes. This allows the appropriate method to be called based on the object type at runtime.

Example:

Practical Examples

Example 1: Shape Hierarchy

In a graphics application, you might have a base class Shape and derived classes like Circle and Rectangle. Inheritance allows these derived classes to reuse code from Shape, while polymorphism allows the program to call the appropriate draw() method based on the actual object type.

Example 2: Employee Management System

In an employee management system, you might have a base class Employee with derived classes Manager and Intern. Inheritance enables shared methods and attributes, while polymorphism allows different calculations of salary based on employee type.

Conclusion

Inheritance and polymorphism are fundamental OOP concepts in C++ that enhance code reusability and flexibility. Inheritance allows for the creation of a new class based on an existing class, promoting code reuse and a hierarchical relationship between classes. Polymorphism provides the ability to use a unified interface while performing different actions based on the object’s actual type. Mastering these concepts is essential for writing efficient and maintainable C++ code.

Similar Questions