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;
}