Virtual functions let a program choose the right function to run when using a base class pointer or reference. This helps when you want different behaviors for different types of objects.
Virtual functions in C++
class Base { public: virtual void functionName(); };
The keyword virtual before a function means it can be overridden in derived classes.
Virtual functions must be members of a class.
sound that can be changed in derived classes.class Animal { public: virtual void sound() { std::cout << "Some sound" << std::endl; } };
Dog overrides the virtual function to provide its own behavior.class Dog : public Animal { public: void sound() override { std::cout << "Bark" << std::endl; } };
Dog version of sound because it is virtual.#include <iostream> int main() { Animal* a = new Dog(); a->sound(); delete a; return 0; }
This program shows how virtual functions let the program call the right sound function depending on the actual object type, even when using base class pointers.
#include <iostream> class Animal { public: virtual void sound() { std::cout << "Some sound" << std::endl; } virtual ~Animal() = default; }; class Dog : public Animal { public: void sound() override { std::cout << "Bark" << std::endl; } }; class Cat : public Animal { public: void sound() override { std::cout << "Meow" << std::endl; } }; int main() { Animal* animal1 = new Dog(); Animal* animal2 = new Cat(); animal1->sound(); // Calls Dog's sound animal2->sound(); // Calls Cat's sound delete animal1; delete animal2; return 0; }
If a function is not virtual, the base class version is called even if the pointer points to a derived object.
Use override keyword in derived classes to help catch mistakes.
Remember to make destructors virtual if you use virtual functions to avoid memory leaks.
Virtual functions allow dynamic choice of function at runtime based on object type.
They enable polymorphism, making code flexible and reusable.
Always use virtual in base class and override in derived classes for clarity.