Sobes.tech
Junior — Middle

Can you give an example of using the virtual keyword in programming?

sobes.tech AI

Answer from AI

The keyword virtual in C++ is used to declare virtual functions, which allows for polymorphism — the method call depends on the object type at runtime, not the pointer or reference type.

Example:

#include <iostream>

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

class Derived : public Base {
public:
    void show() override { // overriding the virtual function
        std::cout << "Derived show" << std::endl;
    }
};

int main() {
    Base* ptr = new Derived();
    ptr->show(); // calls Derived::show thanks to virtual
    delete ptr;
    return 0;
}

In this example, even though the pointer ptr is of type Base*, the method Derived::show is called because the function is declared virtual.