C++ Virtual Functions

Virtual functions in C++ allow achieving runtime polymorphism. When a base class pointer or reference is used to call a derived class function, the virtual function ensures the derived class version is executed.

1. Virtual Function Syntax

A member function is declared virtual in the base class using the `virtual` keyword.

C++
Syntax of virtual function
class Base {
public:
    virtual void display() {
        // base class implementation
    }
};

class Derived : public Base {
public:
    void display() override {
        // derived class implementation
    }
};

2. Virtual Function Example

This example demonstrates how virtual functions enable runtime polymorphism.

C++
Example: Virtual functions
#include <iostream>
using namespace std;

class Base {
public:
    virtual void show() {
        cout << "Base class show function" << endl;
    }
};

class Derived : public Base {
public:
    void show() override {
        cout << "Derived class show function" << endl;
    }
};

int main() {
    Base* basePtr;
    Derived d;
    basePtr = &d;

    basePtr->show(); // Calls Derived's show due to virtual function
    return 0;
}

3. Key Points

1. Virtual functions enable runtime polymorphism. 2. Declared in the base class using `virtual`. 3. Allows derived class function to override base class function. 4. Pointers or references to base class call the derived function if virtual.

4. Common Mistakes

1. Forgetting to declare the base function as virtual. 2. Assuming virtual functions work without a base pointer/reference. 3. Overriding functions with different signatures will not achieve polymorphism.

Conclusion

C++ virtual functions are essential for runtime polymorphism, allowing base class pointers or references to call derived class functions. Proper usage ensures correct behavior in inheritance hierarchies.