Skip to content

Inheritance

Inheritance means a class acquires properties and behaviors of another class. The child class reuses code from the parent class.

Think of it like a child inheriting traits from parents — you get the base features, and can add your own on top.

Syntax

cpp
class Parent {
    // base class
};

class Child : public Parent {
    // derived class
};

Simple Example

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

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

int main() {
    Dog d;
    d.eat();  // inherited from Animal
    d.bark(); // Dog's own method
}

Types of Inheritance in C++

1. Single

cpp
class A {};
class B : public A {};

2. Multilevel

cpp
class A {};
class B : public A {};
class C : public B {}; // C inherits B which inherits A

3. Multiple

cpp
class A {};
class B {};
class C : public A, public B {}; // C inherits both A and B

4. Hierarchical

cpp
class A {};
class B : public A {};
class C : public A {}; // both B and C inherit A

5. Hybrid

cpp
// combination of multiple + hierarchical
class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {}; // Diamond problem

Access Specifiers in Inheritance

Inheritance TypePublic member becomesProtected member becomes
publicpublicprotected
protectedprotectedprotected
privateprivateprivate

Most commonly used is public inheritance in interviews.

Diamond Problem — Virtual Inheritance

cpp
class A { public: void show() { cout << "A" << endl; } };
class B : public A {};
class C : public A {};
class D : public B, public C {}; // ERROR! ambiguity

// Fix: Virtual Inheritance
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {}; // only one copy of A

C++ Specific Points

FeatureDetail
Default inheritanceprivate
Most usedpublic inheritance
Diamond fixvirtual inheritance
Constructor orderParent constructor called first
Destructor orderChild destructor called first

One-liner: "Inheritance allows a derived class to reuse, extend, and modify the behavior of a base class, promoting code reusability."