Virtual Function (C++)
A virtual function is a member function marked with the virtual keyword so that the correct version runs based on the object's actual type at runtime. This is the basis of polymorphism in C++.
C++
Without virtual, a call through a base-class pointer or reference uses the base version of the function. With virtual, C++ picks the derived class's override instead — a mechanism called dynamic dispatch.
A virtual function set to = 0 is a pure virtual function, which makes the class abstract (it cannot be instantiated and must be overridden). Always give a base class with virtual functions a virtual destructor.
Syntax
virtual returnType name();Examples
C++
#include <iostream>
class Animal {
public:
virtual void speak() { std::cout << "..." << std::endl; }
};
class Cat : public Animal {
public:
void speak() override { std::cout << "meow" << std::endl; }
};
int main() {
Animal* a = new Cat();
a->speak();
delete a;
return 0;
}Output:
meow