C++ Polymorphism: Overridable Methods vs Mandatory Interface Methods
Data Structure DesignModel answerLast 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:
- What distinguishes an ordinary virtual function from a pure virtual function? Show the declaration syntax for each.
- 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.
- What does it take for a derived function to override a base one? Mention the pitfalls you would guard against.
- When does a class become abstract? Can a pure virtual function still have a body, and if so, how would that body be reached?
- 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.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core distinction
- A virtual function has a body in the base class. Derived classes may override it, and the base class remains instantiable.
- A pure virtual function is declared with
= 0. It is a mandatory part of the contract: every concrete subclass must override it. Any class that declares or inherits a pure virtual function that has not been overridden is abstract and cannot be instantiated.
class Shape {
public:
virtual ~Shape() = default;
virtual std::string name() const { return "shape"; } // virtual: default provided
virtual double area() const = 0; // pure virtual: must override
};
Both participate in dynamic dispatch identically. The difference lies in whether a default exists and whether the class can be instantiated.
Dynamic dispatch via the vtable
The standard does not mandate vtables, but mainstream compilers use them:
- One vtable per polymorphic class: a static table of function pointers, one slot per virtual function. A derived class copies the base layout and replaces slots it overrides. A pure virtual slot points to a stub (for example
__cxa_pure_virtual) that terminates the program. - One vptr per object: a hidden pointer set up during construction.
- A call such as
p->area()loads the vptr, indexes the slot, and performs an indirect call. The dynamic type picks the function; the static type only determines which names are visible.
Dispatch is not dynamic when:
- The call is on an object by value (
Shape s = circle;slices, sos.area()binds statically). - The call is qualified (
Base::name()). - The call occurs inside a constructor or destructor. While
Base's constructor runs, the object is aBase, so virtual calls resolve toBase's versions. Calling a pure virtual function there is undefined behavior, typically a "pure virtual function called" abort.
How overriding works
A derived member overrides a base virtual function when name, parameter types, cv-qualifiers and ref-qualifiers match. It is then implicitly virtual. Points worth stating:
- Always write
override. Without it, a mismatch such as a missingconstsilently declares a new, unrelated function. With it, the compiler rejects the mistake. finalstops further overriding or derivation and helps the compiler devirtualize.- Covariant return types are allowed:
Derived* clone() constmay overrideBase* clone() const. - Name hiding: declaring any function named
fin the derived class hides all base overloads off. Restore them withusing Base::f;. - Default arguments are bound statically from the static type, not from the overrider. Avoid default arguments on virtual functions.
- Access control is checked against the static type, so a private override can be reached through a public base declaration. The Non-Virtual Interface (NVI) idiom relies on this.
Abstract classes and pure virtual definitions
A class is abstract if it has at least one pure virtual function not overridden by a non-pure function. You cannot create objects of it, but pointers and references to it are fine.
A pure virtual function can have a definition, written outside the class body. Dynamic dispatch never selects it on its own; only a qualified call reaches it:
class Logger {
public:
virtual ~Logger() = default;
virtual void log(const std::string& m) = 0;
};
void Logger::log(const std::string& m) { std::cout << "[base] " << m << '\n'; }
class FileLogger : public Logger {
public:
void log(const std::string& m) override {
Logger::log(m); // explicitly opt in to the shared default
// write to file ...
}
};
This gives "a default you must consciously opt into."
A pure virtual destructor must have a definition, because every derived destructor calls it implicitly. It is the standard trick for making a class abstract when no other function is naturally pure:
class Base { public: virtual ~Base() = 0; };
Base::~Base() = default;
Constructors and destructors
Constructors cannot be virtual. During construction there is no completed object and no vptr to dispatch through, and the caller always names the exact type. For "virtual construction," use a factory function or a virtual clone():
virtual std::unique_ptr<Base> clone() const = 0;
Destructors should be virtual whenever objects may be deleted through a base pointer. Deleting a derived object via a base pointer with a non-virtual destructor is undefined behavior. In practice the derived destructor is skipped, so files, sockets, buffers and owned smart pointers in the derived part leak. Since RAII depends on the correct destructor running, this directly breaks resource management. std::unique_ptr<Base> holding a Derived needs a virtual destructor. (shared_ptr created through make_shared<Derived> captures the right deleter, but relying on that is fragile.)
Guideline (C++ Core Guidelines C.35): a base destructor should be either public and virtual or protected and non-virtual. The second form forbids deletion through the base altogether.
Related hygiene:
- Delete or protect copy and move on polymorphic bases to avoid slicing; offer
clone()when copies are required. - Declaring a destructor suppresses implicit moves, so declare the special members you need.
Choosing between them
| Situation | Choice |
|---|---|
| Subclasses have no sensible common behavior; the base defines a pure interface | Pure virtual |
| There is a reasonable default that most subclasses keep | Virtual with body |
| You want a default but want every subclass to decide consciously | Pure virtual with an out-of-class definition |
| Fixed algorithm skeleton with customizable steps | NVI: public non-virtual function calling private virtual hooks |
| Behavior should never change below some point | final |
Prefer small, focused interfaces, avoid calling virtual functions from constructors and destructors, and always use override.
Cost
- Time: O(1) per call: one extra load and an indirect call. The larger cost is usually lost inlining;
finaland link-time optimization can recover it by devirtualizing. - Space: one vptr per object (typically 8 bytes) and one shared vtable per class.
Common mistakes
- Forgetting a virtual destructor in a polymorphic base.
- Omitting
overrideand accidentally hiding instead of overriding. - Passing polymorphic objects by value, causing slicing.
- Calling virtual functions during construction or destruction and expecting derived behavior.
- Relying on default arguments of virtual functions.
- Under multiple inheritance, forgetting there is one vptr per polymorphic base subobject, with
this-adjusting thunks. - Trying to declare a
staticmember function or a template member functionvirtual; both are ill-formed.