Lecture - Virtual Function
Lecture - Virtual Function
A virtual function is a member function in a base class that you expect to be overridden in
derived classes. It enables runtime polymorphism, which means the correct function is selected
at runtime based on the type of the object, not the type of the pointer or reference.
This concept is commonly used in C++ and other object-oriented programming languages.
#include <iostream>
using namespace std;
class Animal {
public:
virtual void speak() {
cout << "Animal speaks" << endl;
}
};
int main() {
Animal* a = new Dog();
a->speak(); // Outputs: Dog barks
delete a;
}
Key Concepts:
virtual keyword: Declares a function as virtual in the base class.
Polymorphism: The correct function is chosen based on the object's actual type, not the
pointer type.
override keyword (optional but recommended): Helps catch errors by ensuring you're really
overriding a base class function.
When to Use Virtual Functions:
When you have a base class pointer or reference pointing to a derived class object.
When you want to ensure that the derived class's implementation is used.