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 Standardclass 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
virtualinheritance to fix). - Forgetting to use
publicinheritance (defaults toprivatein C++), making base members inaccessible. - Not using
virtualdestructors in the base class when deleting derived objects through pointers.