KatInterview

C++ Polymorphism: Overridable Methods vs Mandatory Interface Methods

Data Structure DesignModel answer
MediumModel answerData Structure Designcpppolymorphismvtable

Last updated

Explain how C++ virtual and pure virtual functions differ, how vtable dispatch works, when a class is abstract, and how virtual destructors affect safe cleanup.

You are designing a class hierarchy in C++ and need to explain the language's polymorphism rules to a teammate.

Answer the following:

  1. What distinguishes an ordinary virtual function from a pure virtual function? Show the declaration syntax for each.
  2. How does a call through a base-class pointer or reference reach the right override at runtime? Describe the typical vtable and vptr mechanism, and name situations where the call is not dispatched dynamically.
  3. What does it take for a derived function to override a base one? Mention the pitfalls you would guard against.
  4. When does a class become abstract? Can a pure virtual function still have a body, and if so, how would that body be reached?
  5. Can constructors be virtual? Should destructors be? Explain the consequences for resource management and what you would do instead where a virtual constructor seems needed.
  6. Give practical guidance on when to choose each kind of function when designing an interface.

Include short code samples where they clarify your points.

Hints

Hint 1

Start from the contract: one kind of function offers a fallback that subclasses may replace, the other forces every concrete subclass to supply its own version.

Hint 2

Think about what the compiler stores per class and per object to make a base-pointer call find the right function, and about what the object's dynamic type is while a base constructor or destructor is running.

Hint 3

For destructors, ask what happens when you delete a derived object through a base pointer whose destructor is not virtual, and what a pure virtual destructor needs in order to link.