C++ Interview Question

What is a virtual function in C++?

Updated 2026-07-10 · Beginner friendly
Quick answer

A virtual function is a member function you mark with the virtual keyword so that the correct version is chosen at run time based on the actual object, not the pointer type. This is how C++ achieves run time polymorphism. It lets a base class pointer call the derived class version of a function.

Why it matters

Without virtual, calling a function through a base pointer uses the base version. With virtual, C++ looks up the real object's type at run time and calls its version, which is essential for polymorphic designs.

class Animal {
public:
    virtual void sound() { std::cout << "..."; }
};
class Dog : public Animal {
public:
    void sound() override { std::cout << "woof"; }
};

Animal* a = new Dog();
a->sound();   // prints woof, thanks to virtual
In the interview

Mention the vtable, a hidden table of function pointers the compiler uses to resolve virtual calls at run time. Also stress that a base class with virtual functions should have a virtual destructor, a favourite follow up.

Want the full C++ guide?

Read every C++ concept with notes, diagrams, and code in one place. Track your progress as you go.

Open the C++ guide All C++ questions