๐ 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 bepublic
,private
, orprotected
.
๐งช 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++
Type | Description |
---|---|
Single | One base class โ One derived class |
Multiple | Multiple base classes โ One derived class |
Multilevel | Derived class becomes a base for another |
Hierarchical | One base class โ Multiple derived classes |
Hybrid | Combination 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 From | Public Inheritance | Private Inheritance | Protected Inheritance |
---|---|---|---|
public | public | private | protected |
protected | protected | private | protected |
private | Not inherited | Not inherited | Not 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.