A virtual function in C++ enables polymorphism by allowing a derived class to override a function in its base class. When a virtual function is called through a base class pointer or reference, the actual function executed is determined at runtime based on the object's type, facilitating dynamic dispatch.