Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

Overriding a virtual function is a mechanism in object-oriented programming that allows a subclass to provide its own implementation of a method declared as virtual in the base class. This ensures polymorphism: when calling the method through a pointer or reference to the base class, the version of the method corresponding to the actual type of the object will be invoked.

Example in C++:

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

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

Base* obj = new Derived();
obj->show(); // Will output "Derived show"