Skip to content

Introduction to Inheritance

๐Ÿ“˜ Introduction to Inheritance in C++

๐Ÿ”‘ Definition:

Inheritance is an Object-Oriented Programming (OOP) concept where one class (child) inherits the properties and behaviors (data members and member functions) of another class (parent).


๐Ÿง  Why Use Inheritance?

  • Code reusability: Avoids rewriting the same code again.
  • Extensibility: Existing classes can be extended with new features.
  • Better structure: Promotes hierarchical class organization.
  • Polymorphism support: Enables dynamic method binding (virtual functions).

๐Ÿ”ง Basic Syntax of Inheritance

class Parent {
// base class code
};

class Child : access-specifier Parent {
// derived class code
};
  • access-specifier can be public, private, or protected.

๐Ÿงช Example: Simple Inheritance

#include <iostream>
using namespace std;

class Animal {
public:
void sound() {
cout << "Animals make sounds" << endl;
}
};

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

int main() {
Dog d;
d.sound(); // Inherited from Animal
d.bark(); // Own function
return 0;
}

โœ… Output:

Animals make sounds  
Dog barks

๐Ÿงฑ Types of Inheritance in C++

TypeDescription
SingleOne base class โ†’ One derived class
MultipleMultiple base classes โ†’ One derived class
MultilevelDerived class becomes a base for another
HierarchicalOne base class โ†’ Multiple derived classes
HybridCombination of two or more types

๐Ÿงฉ Real-Life Analogy

Imagine a Father class has money and a car. The Son class inherits them.
Now the Son doesn’t need to buy new ones โ€” he can reuse what the Father owns.


๐Ÿ” Access Specifiers in Inheritance

Inherited FromPublic InheritancePrivate InheritanceProtected Inheritance
publicpublicprivateprotected
protectedprotectedprivateprotected
privateNot inheritedNot inheritedNot inherited

๐Ÿ“Œ Key Points to Remember

  • Base class = parent class
  • Derived class = child class
  • Inheritance promotes DRY (Don’t Repeat Yourself) principle.
  • Constructor of base class runs before derived class constructor.
  • Destructor of derived class runs before base class destructor.

๐Ÿงพ Summary

  • Inheritance allows a class to reuse code from another class.
  • It makes programs modular, efficient, and organized.
  • Supported in C++ through different types like single, multiple, and multilevel.
  • Achieved using : public, : private, or : protected keywords.