Geek Slack

Learn C++
About Lesson


C++ Inheritance


C++ Inheritance

Inheritance is a mechanism in C++ that allows one class (derived class) to inherit properties and behaviors from another class (base class). It promotes code reuse and allows the derived class to extend or modify the functionality of the base class.

1. Example of Inheritance

Example demonstrating single inheritance:

#include <iostream>
#include <string>

// Base class declaration
class Animal {
protected:
    std::string type;

public:
    // Constructor
    Animal(std::string t) : type(t) {}

    // Member function
    void displayType() {
        std::cout << "Type of animal: " << type << std::endl;
    }
};

// Derived class declaration inheriting from Animal
class Dog : public Animal {
private:
    std::string name;

public:
    // Constructor
    Dog(std::string t, std::string n) : Animal(t), name(n) {}

    // Member function
    void bark() {
        std::cout << "Woof!" << std::endl;
    }

    // Overriding base class function
    void displayType() {
        std::cout << "Type of dog: " << type << std::endl;
    }
};

int main() {
    // Create object of class Dog
    Dog myDog("Canine", "Buddy");

    // Access inherited member function
    myDog.displayType();

    // Access derived class member function
    myDog.bark();

    return 0;
}

2. Types of Inheritance

C++ supports various types of inheritance:

  • Single Inheritance: A derived class inherits from a single base class.
  • Multiple Inheritance: A derived class inherits from multiple base classes.
  • Multilevel Inheritance: Deriving a class from another derived class.
  • Hierarchical Inheritance: Multiple derived classes inheriting from a single base class.
  • Hybrid Inheritance: Combination of multiple and multilevel inheritance.

Conclusion

Inheritance is a powerful feature in C++ that facilitates code reuse and promotes hierarchical relationships between classes. This chapter covered single inheritance, where a derived class inherits from a base class, and discussed various types of inheritance supported by C++. Understanding inheritance allows you to design classes effectively, promoting modularity, extensibility, and code organization in C++ programs.

Join the conversation