Inheritance and Function Overriding

inheritance_funtion_overloading


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++

inheritance

  • 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++

multiple_Inheritance

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

polymorphism

In this example:

  • The base class Animal has a virtual makeSound() function.
  • Derived classes Cat and Dog override makeSound().
  • The animal1 and animal2 pointers call the overridden functions based on the actual object type (Cat or Dog), 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

Abstract_class

Here:

  • Shape is an abstract class with a pure virtual function draw().
  • Both Circle and Square implement draw(), allowing polymorphic behavior when called through the Shape pointer.

Post a Comment

Your comment will be visible after approval.
© TechTestLog. All rights reserved. Premium By Raushan Design
//My script