CurriculumVirtual Functions
Virtual Functions
A <strong>Virtual Function</strong> declared with <code>virtual</code> signals: check the actual object type at runtime and call the correct version.
01Without 'virtual' (The Bug)
Without virtual, function calls are resolved at compile time based on pointer TYPE. This is the wrong behavior through a base pointer.
main.cpp
Terminal
Waiting for execution...
02With 'virtual' (The Fix)
Add virtual to the base. The C++ runtime checks the actual object's vtable and calls the correct version.
main.cpp
Terminal
Waiting for execution...
03Pure Virtual Functions
Pure virtual (= 0) forces all derived classes to implement it. The base becomes abstract and cannot be instantiated.
main.cpp
Terminal
Waiting for execution...
04The vtable Explained
Each class with virtual functions has a vtable: an array of function pointers. Each object has a vptr to its class vtable. Virtual call = vtable lookup.
main.cpp
Terminal
Waiting for execution...
05Virtual Functions in Constructors (Warning)
During base class construction, the vtable is NOT set to the derived class yet. Calling virtual functions in a constructor calls the BASE version - almost always a bug!
main.cpp
Terminal
Waiting for execution...
AI Tutor
Understanding virtual functions is essential for game engines, frameworks, and any polymorphic architecture.