ReviseAlgo Logo

Object-Oriented Programming

Inheritance

Code reuse through inheritance

Interview: Core OOP pillar

Inheritance

Inheritance enables creating specialized classes from existing ones. The derived class inherits members from the base class and can extend or override behavior. C++ supports single and multiple inheritance, plus virtual inheritance to resolve the diamond problem.

Inheritance Types

  • public: Base's public/protected remain public/protected in derived. Most common — models IS-A relationship.
  • protected: Base's public becomes protected in derived.
  • private: All base members become private in derived — models IMPLEMENTED-IN-TERMS-OF.

Constructor/Destructor Order

Base constructor runs first, then derived constructor. Destruction is reverse: derived destructor first, then base. This is why base class destructors that may be called through base pointers must be virtual — otherwise the derived destructor is never called (resource leak).

Interview Corner

Q: Why must base class destructors be virtual when deleting through a base pointer?

A: Without virtual, delete base_ptr calls only the base destructor (static dispatch). The derived destructor never runs — any resources allocated in the derived class leak. With virtual ~Base(), the correct destructor is called via the vtable at runtime. Rule: if a class has virtual functions, its destructor should be virtual.

Common Pitfalls

  • Non-virtual base destructor: Deleting derived objects through base pointers without virtual destructor causes partial destruction and resource leaks.
  • Calling virtual functions in constructors: Virtual dispatch doesn't work during construction — the vtable points to the base class version. The derived override is not called until the derived constructor runs.

Best Practices

  • Always declare base class destructors virtual when the class has virtual functions or is designed for inheritance.
  • Prefer composition over inheritance (HAS-A over IS-A) when the relationship doesn't truly model specialization.