Inheritance in C++

Posted on December 15, 2023 by Vishesh Namdev
Python C C++ Java
C++ Programming

Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a class to inherit properties and behaviors from another class. In C++, the concept of inheritance enables the creation of a new class (derived class or subclass) that incorporates the attributes and functionalities of an existing class (base class or superclass). This process promotes code reuse, extensibility, and the creation of a hierarchical class structure.

...

1. Single Inheritance:

A derived class inherits from only one base class.

class Base {Copy Code
public:
void baseFunction() {
// Base class function
}
};

class Derived : public Base {
public:
void derivedFunction() {
// Derived class function
}
};

2. Multiple Inheritance:

A derived class inherits from more than one base class.

class Base1 {Copy Code
public:
void base1Function() {
// Base1 class function
}
};

class Base2 {
public:
void base2Function() {
// Base2 class function
}
};

class Derived : public Base1, public Base2 {
public:
void derivedFunction() {
// Derived class function
}
};

3. Multilevel Inheritance:

A derived class is used as a base class for another class.

class Grandparent {Copy Code
public:
void grandparentFunction() {
// Grandparent class function
}
};

class Parent : public Grandparent {
public:
void parentFunction() {
// Parent class function
}
};

class Child : public Parent {
public:
void childFunction() {
// Child class function
}
};

4. Hierarchical Inheritance:

Multiple derived classes inherit from a single base class.

class Animal {Copy Code
public:
void eat() {
// Animal class function
}
};

class Dog : public Animal {
public:
void bark() {
// Dog class function
}
};

class Cat : public Animal {
public:
void meow() {
// Cat class function
}
};

5. Hybrid Inheritance:

A combination of multiple inheritance types in a single program.

class A {Copy Code
// Class definition
};

class B : public A {
// Class definition
};

class C : public A {
// Class definition
};

class D : public B, public C {
// Class definition
};

Some Basic Concepts of Inheritance:

(a). Base Class (Superclass):The class whose properties and behaviors are inherited by another class.

(b).Derived Class (Subclass): The class that inherits properties and behaviors from a base class.

(c). Protected Access Specifier: Allows the derived class to access the protected members of the base class.
Public, Private, and Protected Inheritance: Determines the access level of the inherited members in the derived class.

Inheritance promotes code reusability, extensibility, and the creation of a hierarchical structure in the codebase. It establishes relationships between classes, reflecting the "is-a" relationship. Derived classes can reuse the functionality of base classes and, if needed, customize or extend that functionality.