0
0
CppConceptBeginner · 3 min read

Single Inheritance in C++: Definition and Example

In C++, single inheritance means a class derives from one base class only, inheriting its properties and behaviors. It allows a new class to reuse code from an existing class, making programming easier and organized.
⚙️

How It Works

Single inheritance in C++ works like a family tree where a child inherits traits from one parent. Here, the child is a new class called the derived class, and the parent is the base class. The derived class gets all the data and functions of the base class, so you don't have to write them again.

Think of it like a recipe book: if you have a basic cake recipe (base class), and you want to make a chocolate cake (derived class), you start with the basic recipe and add chocolate. This saves time and keeps your code clean.

💻

Example

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

cpp
#include <iostream>
using namespace std;

class Animal {
public:
    void sound() {
        cout << "Animal makes a sound" << endl;
    }
};

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

int main() {
    Dog myDog;
    myDog.sound();  // inherited from Animal
    myDog.bark();   // own function
    return 0;
}
Output
Animal makes a sound Dog barks
🎯

When to Use

Use single inheritance when you want to create a new class that is a specialized version of an existing class. It helps avoid repeating code and makes your program easier to maintain.

For example, in a game, you might have a base class Character and derived classes like Player and Enemy that inherit common features but add their own unique behaviors.

Key Points

  • Single inheritance means one derived class inherits from one base class.
  • Derived class gets all public and protected members of the base class.
  • It promotes code reuse and organization.
  • Helps create a clear relationship between classes.

Key Takeaways

Single inheritance allows a class to inherit from exactly one base class in C++.
It helps reuse code by sharing properties and functions from the base class.
Use it to create specialized classes that extend existing ones without rewriting code.
Derived classes can add new features while keeping base class functionality.
It simplifies program structure and maintenance by showing clear class relationships.