CPP Tutorial



C++ INHERITANCE


Inheritance in C++

Inheritance allows a class (called the derived class) to inherit properties and behaviors (data members and member functions) from another class (called the base class).

Why use inheritance?

  • Reuse code without rewriting it.
  • Create hierarchical relationships between classes.
  • Enable polymorphism (different behaviors via base pointers).

Syntax of Inheritance:

class DerivedClass : access_specifier BaseClass {
  // body of derived class
};
  

access_specifier can be public, private, or protected, affecting the visibility of base members in derived class.

Example of Public Inheritance:

#include <iostream>
using namespace std;

class Animal {
  public:
    void eat() {
      cout << "Eating..." << endl;
    }
};

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

int main() {
  Dog myDog;
  myDog.eat();   // Inherited from Animal
  myDog.bark();  // Defined in Dog

  return 0;
}
  

πŸ–¨οΈ Output:

Eating...
Barking...

πŸ” Explanation:

  • Dog inherits the eat() method from Animal.
  • Dog has its own method bark().
  • So, myDog can call both eat() and bark().

Access Specifiers in Inheritance:

When inheriting, the base class members' accessibility can change depending on the access specifier:

  • public inheritance: public members stay public, protected stay protected, private members remain inaccessible.
  • protected inheritance: public and protected members become protected in derived class.
  • private inheritance: public and protected members become private in derived class.

πŸŽ“ Summary

  • Inheritance helps reuse code and create class hierarchies.
  • Use public inheritance most often for β€œis-a” relationships.
  • Access specifiers in inheritance control visibility of base class members in derived class.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review