Sobes.tech
Junior — Middle

Can you explain what a virtual function in object-oriented programming is?

sobes.tech AI

Answer from AI

A virtual function in object-oriented programming (using C++ as an example) is a member function of a class declared with the keyword virtual. It allows for polymorphism, meaning the function call depends on the type of the object that the pointer or reference points to, rather than the type of the pointer.

When a function is declared virtual, calling it through a pointer or reference to the base class will invoke the version of the function corresponding to the actual type of the object (derived class), if it has been overridden.

Example:

#include <iostream>

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

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

int main() {
    Base* ptr = new Derived();
    ptr->show(); // Will output "Derived show"
    delete ptr;
    return 0;
}

Without virtual, calling ptr->show() would invoke the base class method, ignoring the override in the derived class.

Thus, virtual functions provide dynamic (runtime) polymorphism.