techmore.in

C++ Inheritance

Inheritance in C++ allows a class (called a derived class or child class) to inherit properties and behaviors (data members and member functions) from another class (called a base class or parent class). It promotes code reuse and establishes a relationship between different classes, reflecting a real-world hierarchy.

Types of Inheritance

  1. Single Inheritance: One class inherits from one base class.
  2. Multiple Inheritance: One class inherits from more than one base class.
  3. Multilevel Inheritance: A class is derived from a class that is also derived from another class.
  4. Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
  5. Hybrid Inheritance: A combination of multiple and multilevel inheritance.

Syntax

Here’s an example of single inheritance in C++:

cpp
#include using namespace std; // Base class class Animal { public: void eat() { cout << "This animal is eating." << endl; } }; // Derived class (inherits from Animal) class Dog : public Animal { public: void bark() { cout << "The dog is barking." << endl; } }; int main() { Dog dog1; // Dog can use both its own methods and the inherited methods from Animal dog1.eat(); // Inherited method dog1.bark(); // Dog-specific method return 0; }

Explanation of the Code

  • : This class has a method eat(), which is common to all animals.
  • : The Dog class inherits from Animal and can also define its own methods, like bark().

Access Specifiers in Inheritance

When you inherit from a base class, the access specifier (e.g., public, protected, or private) determines how the base class members are accessible in the derived class:

  1. Public Inheritance: Public members of the base class remain public in the derived class, and protected members remain protected.
  2. Protected Inheritance: Public and protected members of the base class become protected in the derived class.
  3. Private Inheritance: Public and protected members of the base class become private in the derived class.

Example of Protected and Private Inheritance

cpp
class Base { protected: int x; public: void setX(int val) { x = val; } }; // Public inheritance class DerivedPublic : public Base { public: void show() { cout << "Public inheritance, x = " << x << endl; } }; // Private inheritance class DerivedPrivate : private Base { public: void show() { setX(20); // Can still access through methods cout << "Private inheritance, x = " << x << endl; } };

Types of Inheritance (Further Examples)

  • Multiple Inheritance: Inherit from more than one class:
cpp
class Animal { // Base class 1 }; class Mammal { // Base class 2 }; class Dog : public Animal, public Mammal { // Derived class };