0
0
CppConceptBeginner · 3 min read

What is Inheritance in C++: Explanation and Example

In C++, inheritance is a feature that allows one class (called the derived class) to acquire properties and behaviors (data and functions) from another class (called the base class). It helps reuse code and create a relationship between classes.
⚙️

How It Works

Inheritance in C++ works like a family tree where children inherit traits from their parents. The base class is like the parent, and the derived class is like the child. The derived class automatically gets all the data and functions of the base class, so you don't have to write them again.

This means if you have a class Animal with common features like eat() and sleep(), you can create a derived class Dog that inherits these features and adds its own, like bark(). This saves time and keeps your code organized.

💻

Example

This example shows a base class Animal and a derived class Dog that inherits from Animal. The Dog class can use the eat() function from Animal and also has its own bark() function.

cpp
#include <iostream>
using namespace std;

class Animal {
public:
    void eat() {
        cout << "Animal is eating" << endl;
    }
};

class Dog : public Animal {
public:
    void bark() {
        cout << "Dog is barking" << endl;
    }
};

int main() {
    Dog myDog;
    myDog.eat();  // inherited from Animal
    myDog.bark(); // own function
    return 0;
}
Output
Animal is eating Dog is barking
🎯

When to Use

Use inheritance when you want to create a new class that is a specialized version of an existing class. It helps avoid repeating code and models real-world relationships, like a Car is a type of Vehicle.

Common use cases include:

  • Sharing common code among related classes
  • Extending functionality without changing the original class
  • Organizing code in a clear hierarchy

Key Points

  • Inheritance lets a class reuse code from another class.
  • The base class provides common features; the derived class adds or customizes them.
  • It models "is-a" relationships, like Dog is an Animal.
  • Helps keep code clean and organized.

Key Takeaways

Inheritance allows a class to reuse code from another class in C++.
Derived classes get all features of the base class and can add their own.
It models real-world "is-a" relationships to organize code better.
Use inheritance to avoid repeating code and extend functionality easily.