Home > Software engineering >  redefined virtual function call
redefined virtual function call

Time:11-03

#include <iostream>

class Base
{
public:
    virtual void foo() { std::cout << "Base::foo()\n"; };

};

class Derived : public Base
{
public:
    void foo() override 
    {
        std::cout << "Derived::foo()\n";  
        Base::foo();
    }

};

int main()
{
    Derived obj;
    obj.foo();

    return 0;
}

Hello this is my code and I have a question, why I can call Base::foo() in Derived class if I already redefined it in Derived class, why compiler doesn't delete Base::foo in class Derived after redefine?

CodePudding user response:

"why compiler doesn't delete Base::foo in class Derived after redefine"

Because that isn't what virtual and override do. When you provide an override to a base class function, you do not replace it. You are defining a new version for that function. The base class's implementation continues to exist and to be accessible.

Consider the following code. Someone can still use a Base object, and the behaviour should not be changed because Derived exists. The output for base_obj.foo() should continue to be "Base::foo()" regardless of the existance of Derived. :

#include <iostream>

class Base
{
public:
    virtual void foo() { std::cout << "Base::foo()\n"; }
};

class Derived : public Base
{
public:
    void foo() override { std::cout << "Derived::foo()\n"; }
};

int main()
{
    Derived obj;
    obj.foo();

    Base base_obj;
    base_obj.foo();

    return 0;
}

Also consider that multiple classes can derive from Base. I could add a class MyClass : public Base with its own version of foo(), and it should not interfere with how Base or Derived objects behave.

If overriding a member function would cause the base member function to be entirely replaced or removed, it becomes nearly impossible to reason about code without reading carefully every class that derives from it. And unless your IDE provides tools for that, it implies reading all of the code base. It would make it C code that uses polymorphism extremely difficult to understand.

  • Related