Appearance
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 A3. Multiple
cpp
class A {};
class B {};
class C : public A, public B {}; // C inherits both A and B4. Hierarchical
cpp
class A {};
class B : public A {};
class C : public A {}; // both B and C inherit A5. Hybrid
cpp
// combination of multiple + hierarchical
class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {}; // Diamond problemAccess Specifiers in Inheritance
| Inheritance Type | Public member becomes | Protected member becomes |
|---|---|---|
| public | public | protected |
| protected | protected | protected |
| private | private | private |
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 AC++ Specific Points
| Feature | Detail |
|---|---|
| Default inheritance | private |
| Most used | public inheritance |
| Diamond fix | virtual inheritance |
| Constructor order | Parent constructor called first |
| Destructor order | Child destructor called first |
One-liner: "Inheritance allows a derived class to reuse, extend, and modify the behavior of a base class, promoting code reusability."