Virtual Function - heshawacooray/OOP-Heshawa GitHub Wiki

Definition: A virtual function is a member function in a base class that is overridden in a derived class. It ensures that the correct function is called based on the object type at runtime, even when using a base class pointer.

Example code:

#include <iostream>
using namespace std;

class Animal {
public:
    virtual void sound() {
        cout << "Animal makes a sound" << endl;
    }
};

class Dog : public Animal {
public:
    void sound() override {
        cout << "Dog barks" << endl;
    }
};

int main() {
    Animal* animal = new Dog();
    animal->sound();  // Outputs: Dog barks

    delete animal;
    return 0;
}
⚠️ **GitHub.com Fallback** ⚠️