C++ Inheritance

What is Inheritance?

Inheritance allows one class to inherit properties and methods from another class.

It helps reuse code and create relationships between classes.

Basic Syntax

Loading...
Output:

Basic Example

Loading...
Output:

Types of Inheritance

  • Single Inheritance
  • Multilevel Inheritance
  • Multiple Inheritance

Multilevel Inheritance Example

Loading...
Output:

Access Specifiers in Inheritance

Inheritance affects visibility of members.

Loading...
Output:

Protected Members

Protected members can be accessed in derived classes.

Loading...
Output:

Function Overriding

A child class can redefine a function from the parent.

Loading...
Output:

Full Example

Loading...
Output:

Why Inheritance is Important

  • Reuse code
  • Reduce duplication
  • Model relationships
  • Foundation for polymorphism

Common Mistakes

  • Forgetting public keyword
  • Confusing inheritance types
  • Not understanding overriding

Practice

Create a class Vehicle and a derived class Car. Demonstrate inheritance.

Loading...
Output:

Need Help?