Explain inheritance and its types in detail.

SOLUTION....

Inheritance in C++

Definition:
Inheritance lets a derived class reuse and extend the data/behaviour of a base class, modeling an “is-a” relationship (e.g., Dog is a Animal). It improves reuse, reduces duplication, and enables polymorphism.

Basic syntax:

 

Access effects (visibility mode):

  • public inheritance: base public → derived public, base protected → derived protected.

  • protected inheritance: base public/protected → derived protected.

  • private inheritance: base public/protected → derived private.

  • Base private members aren’t directly accessible in derived (they still exist via the base subobject).

Ctor/Dtor order:
Base constructor runs first, then derived. Destruction is reverse: derived then base. For polymorphic bases, prefer a virtual destructor.

Overriding & polymorphism:
Mark base functions virtual, override in derived with override, and call through base pointers/references to get runtime polymorphism.

Types of Inheritance (with tiny C++ sketches)

1) Single Inheritance

One base → one derived.

2) Multilevel Inheritance

A chain of derivations.

3) Multiple Inheritance

Derived class inherits from multiple bases.

4) Hierarchical Inheritance

Multiple derived classes from the same base.

5) Hybrid Inheritance

A mix (e.g., multilevel + multiple). Often involves virtual inheritance to resolve diamonds.


#include <iostream>
using namespace std;

class Shape {
public:
    virtual double area() const = 0;   // polymorphic base
    virtual ~Shape() = default;
};

class Rectangle : public Shape {
    double w, h;
public:
    Rectangle(double W, double H) : w(W), h(H) {}
    double area() const override { return w * h; }
};

class Square : public Rectangle {      // multilevel (Square is a Rectangle)
public:
    Square(double s) : Rectangle(s, s) {}
};

int main() {
    Shape* p = new Square(5);
    cout << p->area() << '\n';         // 25
    delete p;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.