What are virtual functions and polymorphism in C++?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid C++ basics — a prerequisite for any developer role.
Answer
Virtual functions enable runtime polymorphism — the correct function is selected based on the actual type of the object pointed to (dynamic dispatch), not the declared type. How it works: when a class declares a virtual function, the compiler creates a vtable (virtual dispatch table) — an array of function pointers for all virtual functions. Each object of that class has a hidden vptr (vtable pointer) set in the constructor. At runtime, function calls via pointer/reference go through the vtable. class Shape { public: virtual double area() const = 0; // pure virtual virtual void draw() const { std::cout << "Drawing shape\n"; } virtual ~Shape() = default; }; class Circle : public Shape { double r; public: Circle(double r) : r(r) {} double area() const override { return 3.14159 * r * r; } void draw() const override { std::cout << "Drawing circle\n"; } }; class Square : public Shape { double side; public: Square(double s) : side(s) {} double area() const override { return side * side; } }; // Runtime polymorphism: std::vector<std::unique_ptr<Shape>> shapes; shapes.push_back(std::make_unique<Circle>(5)); shapes.push_back(std::make_unique<Square>(4)); for (auto& s : shapes) { std::cout << s->area() << "\n"; // Correct area() called! }. override keyword (C++11): explicitly marks a function as overriding a virtual — compiler error if no matching virtual base function. Always use override. final keyword: prevents further overriding: void draw() const final;. Pure virtual: = 0 — makes class abstract (cannot instantiate). Derived class must implement all pure virtuals to be concrete. Non-virtual function hiding: if a non-virtual function is "overridden" in derived class, it hides (not overrides) the base version.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex C++ answers easy to follow.