Inheritance in C++ with Types and Examples

Inheritance in C++

Inheritance is a powerful feature of Object-Oriented Programming that allows a class to acquire properties and behaviors of another class. It promotes code reusability, reduces redundancy, and helps build hierarchical relationships between classes.


What is Inheritance?

Inheritance is a mechanism where:

  • An existing class (base class)
  • Is extended by a new class (derived class)

The derived class can use:

  • Data members
  • Member functions

of the base class.


Basic Terminology

  • Base Class / Parent Class – The class whose properties are inherited
  • Derived Class / Child Class – The class that inherits properties

Syntax of Inheritance in C++

class DerivedClass : access_specifier BaseClass {
    // body
};

Types of Inheritance in C++


1. Single Inheritance

One derived class inherits from one base class.

Example:
Class Car inherits from Vehicle

Use Case:
Simple hierarchical relationships.


2. Multiple Inheritance

A class inherits from more than one base class.

Example:
Class Student inherits from Person and Academic

Note:
May cause ambiguity (diamond problem).


3. Multilevel Inheritance

A class is derived from another derived class.

Example:
Vehicle → Car → SportsCar


4. Hierarchical Inheritance

Multiple classes inherit from a single base class.

Example:
Shape → Circle, Rectangle


5. Hybrid Inheritance

Combination of two or more types of inheritance.

Example:
Combination of multiple and multilevel inheritance.


Access Specifiers in Inheritance

Access SpecifierVisibility
publicAccessible everywhere
protectedAccessible in derived classes
privateNot accessible in derived classes

Advantages of Inheritance

  • Code reusability
  • Reduced development time
  • Easy maintenance
  • Improved scalability
  • Better program structure

Real-World Example

Real World:

  • Base Class: Employee
  • Derived Class: Manager

Manager inherits:

  • Name
  • Salary

And adds:

  • Bonus
  • Department

Method Overriding

Derived class can redefine a function of the base class to provide specific behavior.

Used for runtime polymorphism.


Common Problems in Inheritance

  • Diamond problem
  • Tight coupling
  • Overuse of inheritance

These can be handled using virtual base classes and proper design.


Applications of Inheritance

  • Banking systems
  • Payroll software
  • Game development
  • GUI applications
  • Framework design

Conclusion

Inheritance enables classes to reuse and extend functionality efficiently. By understanding its types, syntax, and advantages, students can design structured and scalable C++ programs. Inheritance also serves as a foundation for polymorphism.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *