inheritance in cpp
inheritance in cpp
Introduction
Inheritance is a core feature of Object-Oriented Programming (OOP) in C++. It allows a class (derived class) to inherit properties and behaviors from another class (base class). This promotes code reusability and logical hierarchy.
Inheritance allows you to create a new class based on an existing class. The new class gets access to the data members and member functions of the existing class.
Key Points:
Base class (Parent) – The class whose features are inherited
Derived class (Child) – The class that inherits features from the base class
Access specifiers: public
, protected
, private
Single Inheritance – One base and one derived class
Multiple Inheritance – One derived class inherits from multiple base classes
Multilevel Inheritance – A class derived from another derived class
Hierarchical Inheritance – Multiple derived classes inherit from a single base class
Hybrid Inheritance – Combination of two or more types
#include <iostream>
using namespace std;
// Base class
class Developer {
public:
string name;
string skills;
void work() {
cout << name << " is coding using " << skills << "." << endl;
}
};
// Derived class
class TeamLead : public Developer {
public:
int teamSize;
void manageTeam() {
cout << name << " is managing a team of " << teamSize << " developers." << endl;
}
};
int main() {
TeamLead lead;
lead.name = "Alice";
lead.skills = "C++ and Python";
lead.teamSize = 5;
lead.work();
lead.manageTeam();
return 0;
}
Output:
Alice is coding using C++ and Python.
Alice is managing a team of 5 developers.
Public inheritance – Public and protected members remain accessible as they are.
Protected inheritance – Public and protected members of base become protected in derived.
Private inheritance – Public and protected members of base become private in derived.
Code reusability – Avoid rewriting code for similar classes
Extensibility – Easily extend base class features in new classes
Maintainability – Centralized code makes updates easier
Real-world modeling – Models hierarchical relationships like Employee → Manager
Inheritance allows you to build new classes on top of existing ones, saving time and effort.
Base class provides common functionality
Derived class extends or customizes it
This is a key principle of OOP that simplifies large program design.