0
0
C++programming~5 mins

Why inheritance is used in C++

Choose your learning style9 modes available
Introduction

Inheritance lets one class get features from another class. It helps reuse code and organize related things together.

When you want to create a new class that is a type of an existing class.
When you want to share common code between classes to avoid repeating it.
When you want to build a clear relationship between general and specific things.
When you want to extend or customize behavior of an existing class.
When you want to group similar objects under a common interface.
Syntax
C++
class DerivedClass : accessSpecifier BaseClass {
  // members and methods
};

DerivedClass is the new class that inherits from BaseClass.

accessSpecifier is usually public to keep base class features accessible.

Examples
Dog inherits from Animal, so Dog can eat and bark.
C++
class Animal {
public:
  void eat() {
    std::cout << "Eating" << std::endl;
  }
};

class Dog : public Animal {
public:
  void bark() {
    std::cout << "Barking" << std::endl;
  }
};
Car inherits from Vehicle, so Car can start and honk.
C++
class Vehicle {
public:
  void start() {
    std::cout << "Vehicle started" << std::endl;
  }
};

class Car : public Vehicle {
public:
  void honk() {
    std::cout << "Car honks" << std::endl;
  }
};
Sample Program

This program shows how Dog inherits the eat() method from Animal and also has its own bark() method.

C++
#include <iostream>

class Animal {
public:
  void eat() {
    std::cout << "Animal is eating" << std::endl;
  }
};

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

int main() {
  Dog myDog;
  myDog.eat();  // inherited from Animal
  myDog.bark(); // own method
  return 0;
}
OutputSuccess
Important Notes

Inheritance helps avoid rewriting the same code in multiple classes.

Use public inheritance to keep base class features accessible to users of the derived class.

Derived classes can add new features or change existing ones.

Summary

Inheritance lets a class get features from another class.

It helps reuse code and organize related classes.

Use inheritance when you want to model "is-a" relationships.