What is Inheritance in C++: Explanation and Example
inheritance is a feature that allows one class (called the derived class) to acquire properties and behaviors (data and functions) from another class (called the base class). It helps reuse code and create a relationship between classes.How It Works
Inheritance in C++ works like a family tree where children inherit traits from their parents. The base class is like the parent, and the derived class is like the child. The derived class automatically gets all the data and functions of the base class, so you don't have to write them again.
This means if you have a class Animal with common features like eat() and sleep(), you can create a derived class Dog that inherits these features and adds its own, like bark(). This saves time and keeps your code organized.
Example
This example shows a base class Animal and a derived class Dog that inherits from Animal. The Dog class can use the eat() function from Animal and also has its own bark() function.
#include <iostream> using namespace std; class Animal { public: void eat() { cout << "Animal is eating" << endl; } }; class Dog : public Animal { public: void bark() { cout << "Dog is barking" << endl; } }; int main() { Dog myDog; myDog.eat(); // inherited from Animal myDog.bark(); // own function return 0; }
When to Use
Use inheritance when you want to create a new class that is a specialized version of an existing class. It helps avoid repeating code and models real-world relationships, like a Car is a type of Vehicle.
Common use cases include:
- Sharing common code among related classes
- Extending functionality without changing the original class
- Organizing code in a clear hierarchy
Key Points
- Inheritance lets a class reuse code from another class.
- The base class provides common features; the derived class adds or customizes them.
- It models "is-a" relationships, like Dog is an Animal.
- Helps keep code clean and organized.