Sobes.tech
Junior — Middle

Can you explain the purpose and function of the 'virtual' keyword in object-oriented programming?

sobes.tech AI

Answer from AI

The keyword virtual in C++ is used to declare virtual functions — class methods that can be overridden in derived classes and are called dynamically (at runtime), not statically (at compile time). This is the foundation of polymorphism in object-oriented programming.

When a function is declared as virtual in a base class, calling this function through a pointer or reference to the base class will invoke the version of the function corresponding to the actual type of the object (even if the variable's type is the base).

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" thanks to virtual
    delete ptr;
    return 0;
}

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

Thus, virtual enables dynamic polymorphism, which is important for flexible software architecture.