3

Assuming I have code like this:

struct Base1 {
    virtual void foo() = 0;
};

struct Base2 {
    virtual void foo() = 0;
};

struct Derived : Base1, Base2 {
    void foo() override {}
};

I am trying to produce a single override for several functions of different base classes with same name/signature.

Is such an overriding legal and well-defined in c++?

Andrei R.
  • 2,374
  • 1
  • 13
  • 27

1 Answers1

3

Is such an overriding legal and well-defined in c++?

Yes, it is perfectly legal and well defined as long as you override the virtual function in the derived class.
If you create an object of Derived structure and invoke the foo function it will invoke the overridden function.

The compiler will always search the called function from local to the global scope. So here compiler will check if foo is defined in the Derived scope if not found it will check in the Base scope and since you have provided the definition of foo in the derived scope the compiler won't check Base scope.

Try this code and you will get a better idea. The output will be This is derived.

#include <iostream>
using namespace std;
struct Base1 {
    virtual void foo() {
        cout << "This is base1" << endl;
    }
};

struct Base2 {
    virtual void foo() {
        cout << "This is base2" << endl;
    }
};

struct Derived : Base1, Base2 {
    void foo() {
        cout << "This is derived" << endl;
    }
};

int main() {
    Derived d;
    d.foo();
    return 0;
}
ani627
  • 5,578
  • 8
  • 39
  • 45