C++ Virtual Functions Interview Questions
Last updated 2026-11-19
Virtual functions are the mechanism behind run-time polymorphism in C++, and interviewers use them to check whether you understand dispatch rather than just syntax. Expect to explain the vtable and vptr, predict the output of a base pointer calling an overridden function, and say why a base destructor should be virtual.
The answers below stay at the level of what the standard guarantees and what typical compilers do. The vtable layout is an implementation detail, but "one vptr per polymorphic object pointing at a per-class table of function addresses" is the accepted explanation and is what you should say. For the wider object model see C++ OOPS questions.
| Core idea | Dispatch on dynamic type through the vtable |
|---|---|
| Keywords | virtual, override, final, = 0 |
| Standard | C++11 onwards |
Rules that decide most output questions
- A call is dynamically dispatched only through a pointer or reference to a base, and only if the function is virtual.
- Default arguments are bound statically, using the type of the pointer, not the dynamic type.
- A function that overrides a virtual one is itself virtual, even without the keyword.
- Overload resolution happens on the static type first. Dispatch then picks the final overrider.
- Calls inside constructors and destructors do not reach more-derived overrides.
What to say about cost
A polymorphic object carries one hidden pointer, so its size grows by a pointer, and each virtual call is an indirect call that usually cannot be inlined. In hot loops this matters; in most application code it does not. Mention devirtualisation: if the compiler can see the exact type, or the class or function is final, it can call directly.
C++ Virtual Functions Interview Questions: questions with worked answers
1 What is a virtual function and why do we need it?
easyA virtual function is a member function whose call through a base-class pointer or reference is resolved at run time using the object's actual type. Without virtual, the compiler picks the function from the static type, so a Base* to a Derived object would call Base::f. Virtual functions let you write code against a base interface (a list of Shape*) and have each concrete class supply its behaviour.
2 Explain how vtable and vptr work.
mediumFor every class with virtual functions the compiler builds a vtable: an array of function addresses for the class's virtual functions, with entries replaced by overriders in derived classes. Each object of such a class stores a hidden vptr, set by the constructor to point to its class's vtable. A virtual call loads the vptr, indexes the table at the function's slot and jumps there. With multiple inheritance an object can carry several vptrs, one per polymorphic base. Static functions and non-virtual functions do not use the table.
3 Predict the output.
mediumThe output is B and then A. p points to a B object, and f is virtual, so the call resolves to B::f. The second call is on a copy: "A a = *p" slices the B object into an A, so a.f() calls A::f. Sliced objects have the vptr of A.
cppstruct A { virtual void f() { std::cout << "A\n"; } }; struct B : A { void f() override { std::cout << "B\n"; } }; int main() { A* p = new B; p->f(); // B A a = *p; a.f(); // A // delete p would be UB: A has no virtual destructor }4 Why must the base destructor be virtual? What happens if it is not?
mediumIf a derived object is deleted through a base pointer and the base destructor is not virtual, the behaviour is undefined. In practice only the base destructor runs, so derived members (strings, buffers, handles) are never destroyed and leak. A virtual destructor makes the delete dispatch to the most derived destructor, which then runs the base destructor automatically. Rule of thumb: a class with any virtual function should have a virtual destructor, unless instances are never deleted via base pointers (then make it protected and non-virtual). std::shared_ptr<Base> created with make_shared<Derived> destroys correctly even without it, because it remembers the concrete deleter, but unique_ptr<Base> does not.
5 What is the override keyword and what does final do?
mediumoverride tells the compiler that this function must override a virtual function in a base class, so a typo in the name or a mismatch in const or parameter types becomes a compile error instead of a new, unrelated function. final on a virtual function forbids further overriding; final on a class forbids deriving from it. Both help the optimiser as well, since final lets calls be devirtualised.
cppstruct B { virtual void f(int) const; }; struct D : B { void f(int) override; // error: missing const void f(int) const override; // ok }; struct E final : D {};6 Predict the output: default arguments and virtual functions.
mediumIt prints "B 10". Dispatch is dynamic, so B::f runs, but default arguments are resolved at compile time from the static type of the expression. p is an A*, so the default value from A (10) is used even though the body is B's. Avoid redefining default arguments on overriders.
cppstruct A { virtual void f(int x = 10) { std::cout << "A " << x << "\n"; } }; struct B : A { void f(int x = 20) override { std::cout << "B " << x << "\n"; } }; int main() { A* p = new B; p->f(); delete p; } // B 107 Can you call a virtual function from a constructor? What about a destructor?
mediumYou can, but it never reaches a more-derived override. During Base's constructor the object's dynamic type is Base, and during its destructor the derived part is already gone, so the call binds to Base's version. If that version is pure virtual and has no definition, the program has undefined behaviour and commonly aborts. Do real initialisation that needs virtual behaviour in an init() method after construction, or use a factory function.
8 What is a pure virtual function, and can an abstract class have a constructor?
mediumA pure virtual function is declared "virtual void f() = 0;" and makes the class abstract: you cannot create objects of it, only pointers or references. An abstract class can and often does have a constructor and data members, run when a derived class is constructed. Derived classes become concrete only when they override every pure virtual function. A pure virtual function may also have a body, called via the qualified name, and a pure virtual destructor must have one.
9 What is the cost of virtual functions, and how can the compiler devirtualise a call?
hardCosts: an extra pointer per object, an indirect call through the vtable, and loss of inlining. The CPU predicts the indirect branch well when the same type is used repeatedly, so the practical hit is mostly inlining and cache effects. Compilers devirtualise when the dynamic type is known (a local object, a "new" in view, a final class or function) or through whole-program profile feedback. Design alternatives include templates (static polymorphism, CRTP), std::variant with std::visit and plain function pointers.
10 What is CRTP and how does it compare with virtual functions?
hardThe Curiously Recurring Template Pattern has a class derive from a template instantiated with itself: struct D : Base<D>. The base can then call derived functions through static_cast<D*>(this), resolved at compile time with no vtable and full inlining. The trade-off is that there is no common runtime base, so you cannot keep a mixed container of different instantiations of the base in one vector. Use virtual functions when the set of types is open at run time and CRTP when it is known at compile time and speed matters.
cpptemplate <class D> struct Shape { double area() const { return static_cast<const D*>(this)->areaImpl(); } }; struct Sq : Shape<Sq> { double s; double areaImpl() const { return s * s; } };11 Can you override a function that is not virtual? What is name hiding?
mediumDeclaring a function with the same name in the derived class does not override it; it hides every base function of that name. Calls through a Base pointer still use Base::f, and calls through a Derived object or pointer see only Derived::f and its overloads, so a Base overload with different parameters becomes inaccessible by name until you write "using Base::f;". This is why mismatched signatures should be caught with override.
12 What happens with a virtual function and multiple inheritance?
mediumA class with two polymorphic bases has a vptr for each base subobject, and the compiler generates small adjuster thunks so that "this" is shifted to the right subobject when you call through the second base. Casting a Derived* to its second base changes the pointer value, which is why you must use static_cast and never reinterpret_cast or C casts between them. If two bases declare the same virtual function, the derived class overrides both with one function, or it must disambiguate with different names.
13 Can static member functions, constructors or templates be virtual?
easyStatic member functions cannot be virtual since they have no this pointer. Constructors cannot be virtual because the vptr is not established until construction. Member function templates cannot be virtual because the vtable has a fixed number of slots known at compile time, and a template could produce unlimited instantiations. Destructors, operators and ordinary member functions can be virtual.
14 What does dynamic_cast do and what does it need to work?
harddynamic_cast checks at run time that a base pointer or reference really refers to the requested derived type. It needs the source type to be polymorphic, because it reads type information (RTTI) via the vptr. A failed pointer cast returns nullptr and a failed reference cast throws std::bad_cast. dynamic_cast<void*> returns the address of the most derived object. Frequent use is a design smell: prefer a virtual function. It also costs more than static_cast and can be disabled by -fno-rtti.
cppif (auto* d = dynamic_cast<Derived*>(basePtr)) { d->onlyInDerived(); }15 What is the size of an object with virtual functions?
mediumIt is the size of the data members plus a hidden vptr, usually 8 bytes on 64-bit platforms, subject to alignment padding. So struct S { virtual void f(); }; has sizeof 8 on 64-bit, while an otherwise identical struct without virtual is 1. Adding a second virtual function does not add another pointer because they share one vtable. The exact value is implementation defined.
Frequently asked questions
Is the vtable part of the C++ standard?
No. The standard defines the behaviour of virtual calls, not how they are implemented. The vtable and vptr model is how mainstream compilers do it.
What is the difference between overloading and overriding?
Overloading is same name with different parameters at compile time. Overriding replaces a virtual function with the same signature in a derived class, resolved at run time.
Do virtual functions hurt performance a lot?
Usually not noticeably, but they block inlining and add an indirect call, which matters in tight loops. Measure before redesigning.
Where do I practise more OOPS output questions?
Try C++ OOPS questions and C programming output questions for the same tracing skill.
Related guides
More in Programming Language Interview Questions by Language
- Core Java Interview Questions for Freshers
- Entity Framework Core Interview Questions
- Java 8 Streams and Lambdas Interview Questions
- Java Coding Interview Questions
- Java Collections Interview Questions
- Java Concurrency Utilities Interview Questions
- Java Exception Handling Interview Questions
- Java Garbage Collection Interview Questions
- Java Generics Interview Questions
- Java HashMap Internals Interview Questions
- Java Interfaces and Abstract Classes Interview Questions
- Java Interview Questions and Answers