C++ Inheritance

Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and behaviors (methods) from another class. This promotes code reusability and establishes a relationship between classes.

Key Topics

1. Types of Inheritance

There are several types of inheritance in C++:

  • Single Inheritance: A derived class inherits from a single base class.
  • Multiple Inheritance: A derived class inherits from multiple base classes.
  • Multilevel Inheritance: A derived class inherits from another derived class.
  • Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
  • Hybrid Inheritance: A combination of two or more types of inheritance.

2. Base and Derived Classes

The class from which properties are inherited is called the base class, while the class that inherits those properties is called the derived class.

Example: Base and Derived Classes

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

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

Code Explanation: The class Animal is the base class, and Dog is the derived class that inherits from Animal.

3. Access Specifiers

Access specifiers control the visibility of base class members in derived classes. The three main access specifiers are:

  • public: Members are accessible from outside the class.
  • protected: Members are accessible in the derived class and its subclasses but not from outside.
  • private: Members are accessible only within the class itself.

4. Virtual Functions

Virtual functions allow derived classes to override methods of the base class, enabling polymorphism. This means that the correct method is called based on the object type, not the reference type.

Example: Virtual Functions

class Animal {
public:
    virtual void sound() {
        std::cout << "Animal sound";
    }
};

class Dog : public Animal {
public:
    void sound() override {
        std::cout << "Barking...";
    }
};

Code Explanation: The sound function in the Animal class is declared as virtual, allowing the Dog class to override it. When called through a base class pointer, the derived class's version of the function will be executed.

Key Takeaways

  • Inheritance allows for code reusability and establishes a relationship between classes.
  • There are various types of inheritance, including single, multiple, multilevel, hierarchical, and hybrid inheritance.
  • Access specifiers (public, protected, private) control the visibility of base class members in derived classes.
  • Virtual functions enable polymorphism, allowing derived classes to provide specific implementations of base class methods.
  • Understanding inheritance is crucial for effective object-oriented programming in C++.