Sobes.tech
Junior — Middle

What does overriding a method in object-oriented programming mean?

sobes.tech AI

Answer from AI

Method overriding is an object-oriented programming mechanism that allows a subclass to provide its own implementation of a method that is already defined in the base class. This enables changing or extending the behavior of inherited methods.

To override a method in C++, the base method must be declared as virtual (virtual), and in the derived class, you can define a method with the same signature, which will be called when working with an object through a pointer or reference to the base class.

Example:

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

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

int main() {
    Base* b = new Derived();
    b->show(); // calls Derived::show thanks to the virtual mechanism
    delete b;
}

Thus, overriding allows implementing polymorphism and dynamic method invocation.