Inheritance

Inheritance

In C++, inheritance allows you to create new classes (derived classes) based on existing classes (base classes). The derived classes inherit attributes and behaviors from their base classes and can extend or modify them as needed. Here’s a basic example of inheritance in C++:

Example:

#include <iostream>
#include <string>
using namespace std;

// Base class
class Vehicle {
  public: 
    string brand = "Toyota";
    void honk() {
      cout << "Rataataaaa! \n" ;
    }
};

// Derived class
class Car: public Vehicle {
  public: 
    string model = "Supra";
};

int main() {
  Car myCar;
  myCar.honk();
  cout << myCar.brand + " " + myCar.model;
  return 0;
}

Output:

Rataataaaa! 
Toyota Supra

Why And When To Use “Inheritance”?

It is useful for code reusability ,Maintenance: reuse attributes and methods of an existing class when you create a new class.

Multilevel Inheritance

Multilevel inheritance in C++ refers to a situation where a derived class inherits from another derived class, creating a chain or hierarchy of inheritance. In multilevel inheritance, each derived class serves as a base class for the next level of derived classes, forming a sequence of classes.

Example:

#include <iostream>
using namespace std;

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

// Derived class inheriting from Animal
class Dog : public Animal {
public:
    void bark() {
        cout << "Dog is barking." << endl;
    }
};

// Derived class inheriting from Dog
class GermanShepherd : public Dog {
public:
    void guard() {
        cout << "German Shepherd is guarding." << endl;
    }
};

int main() {
    // Create an object of the derived class GermanShepherd
    GermanShepherd gs;

    // Access methods from different levels of inheritance
    gs.eat();        // Method from Animal class
    gs.bark();       // Method from Dog class
    gs.guard();      // Method from GermanShepherd class

    return 0;
}

Output:

Animal is eating.
Dog is barking.
German Shepherd is guarding.

Multiple Inheritance

Multiple inheritance in C++ is a feature that allows a class to inherit properties and behaviors from more than one base class. This means a class can have multiple parent classes, and it inherits features from all of them. However, multiple inheritance can lead to ambiguity and complexity, so it should be used judiciously.

Example:

#include <iostream>
using namespace std;

// Base class
class Animal {
  public:
    void my1Function() {
      cout << "Animal is Dog\n" ;
    }
};

// Another base class
class Dog {
  public:
    void my2Function() {
      cout << "Dog is Guarding\n" ;
    }
};

// Derived class
class Guarding: public Animal, public Dog {
};

int main() {
  Guarding mydog;
  mydog.my1Function();
  mydog.my2Function();
  return 0;
}

Output:

Animal is Dog
Dog is Guarding

    Leave a Reply

    Your email address will not be published.

    Need Help?