Single inheritance

Single inheritance in C++ is a concept where a class (derived class) inherits from only one base class. This allows the derived class to inherit attributes and methods from the base class.

Syntax

class Base {
    // Base class members
};

class Derived : public Base {
    // Derived class members
};

Example

#include <iostream>
using namespace std;

class Animal {
public:
    void eat() {
        cout << "Eating..." << endl;
    }
};

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

int main() {
    Dog myDog;
    myDog.eat();  // Inherited from Animal
    myDog.bark(); // Specific to Dog
    return 0;
}

Key Points

  1. Reusability: Single inheritance allows code reusability by inheriting existing functionalities from a base class.
  2. Simplicity: It simplifies the relationship between classes, making it easier to understand and manage.
  3. Access Specifiers: The access specifier (public, protected, private) determines the accessibility of base class members in the derived class.