🎭 C++ Virtual Functions – One Name, Many Forms at Runtime
In C++, a virtual function lets you create a function in a base class and override it in a derived class — then call the correct version at runtime using a base class pointer. It’s a smart way to get polymorphism working! 🧠
🔍 What is a Virtual Function?
A virtual function is a member function in a base class that you expect to be redefined in derived classes. It’s marked with the keyword virtual
. At runtime, C++ figures out which function to run based on the actual object type — not just the pointer type.
💡 Syntax
class Base { public: virtual void speak() { // base version } };
🔧 Example: Using Virtual Function
#include <iostream> using namespace std; class Animal { public: virtual void speak() { cout << "Animal speaks" << endl; } }; class Cat : public Animal { public: void speak() override { cout << "Cat meows" << endl; } }; int main() { Animal* pet; Cat kitty; pet = &kitty; pet->speak(); // Calls Cat's version at runtime return 0; }
📌 Key Points
- Declared using the
virtual
keyword in the base class - Used to achieve runtime polymorphism
- Enables dynamic method resolution
- Usually overridden using
override
keyword in derived class
⚠️ Virtual vs Non-Virtual
- Virtual: Resolved at runtime (dynamic binding)
- Non-virtual: Resolved at compile time (static binding)
🧠 Why Use Virtual Functions?
- Allows different behavior for the same function name
- Makes code more flexible and extensible
- Used heavily in real-world object-oriented systems
🧾 Summary
- Use virtual in the base class when expecting overriding
- Pointer to base class calls correct derived method at runtime
- This is the heart of runtime polymorphism
- One name, many forms — that’s virtual magic! ✨