Inheritance allows a new class (derived class) to inherit properties and behaviors from an existing class (base class). This is useful for creating a hierarchical class structure, enabling code reuse and representing relationships between classes.
Single and Multiple Inheritance
- Single Inheritance: In single inheritance, a derived class inherits from one base class.
Example: Single Inheritance in C++
- Multiple Inheritance: In multiple inheritance, a derived class inherits from more than one base class. This can introduce complexity due to potential ambiguities, which is why it’s used cautiously.
Example: Multiple Inheritance in C++
In this example, the FlyingFish
class inherits both the fly()
function from Bird
and the swim()
function from Fish
, enabling it to use both functions.
Polymorphism
Polymorphism allows objects to be treated as instances of their base class, enabling flexibility in calling overridden functions. In C++, this is typically implemented through virtual functions and dynamic binding.
2. Function Overriding and Virtual Functions
Function Overriding: When a derived class provides a specific implementation for a function already defined in its base class.
Virtual Functions: A virtual function in the base class allows derived classes to override it, and the appropriate function is chosen based on the actual object type at runtime.
Example: Function overriding using virtual functions
In this example:
- The base class
Animal
has a virtualmakeSound()
function. - Derived classes
Cat
andDog
overridemakeSound()
. - The
animal1
andanimal2
pointers call the overridden functions based on the actual object type (Cat
orDog
), demonstrating dynamic binding.
Abstract Classes and Pure Virtual Functions
An abstract class in C++ is a class that cannot be instantiated and typically contains at least one pure virtual function. A pure virtual function is declared by assigning = 0
to it, forcing derived classes to provide their own implementations.
Example: Abstract class with a pure virtual function
Here:
Shape
is an abstract class with a pure virtual functiondraw()
.- Both
Circle
andSquare
implementdraw()
, allowing polymorphic behavior when called through theShape
pointer.