Core Module
12 min forge

C++ Inheritance

Creating hierarchical relationships between classes to reuse code.

C++ Inheritance

πŸ“˜ What is it

Inheritance allows a new class (Derived Class) to inherit the properties and behavior of an existing class (Base Class). It provides code reusability and builds a hierarchical relationship.

⚑ When to use

Use inheritance when an "IS-A" relationship exists between classes (e.g., a Dog IS-A Animal).

🧠 Time complexity

  • Object Creation: $O(1)$ (plus base class constructor).
  • Call: $O(1)$.

πŸ’» Code example

cpp Standard
class Animal { public: void eat() { std::cout << "Eating..." << endl; } }; class Dog : public Animal { public: void bark() { std::cout << "Barking..." << endl; } }; int main() { Dog myDog; myDog.eat(); // Inherited myDog.bark(); // Own method }

❌ Common mistakes

  • Diamond Problem: Multiple inheritance resulting in ambiguity (use virtual inheritance to fix).
  • Forgetting to use public inheritance (defaults to private in C++), making base members inaccessible.
  • Not using virtual destructors in the base class when deleting derived objects through pointers.