Having
#include <iostream>
using namespace std;
class A {
public:
virtual void foo() {
cout << "A" << endl;
}
};
class B : public A {
public:
void foo() {
cout << "B" << endl;
}
};
class C : public B {
public:
void foo() {
cout << "C" << endl;
}
};
int main() {
C c;
B* b = &c;
b->foo();
return 0;
}
The output is C
, but I expected B
.
I didn't declare B::foo()
with the virtual
modifier, so I expect the function call to be determined by the static type (no polymorphism).
Why is C::foo()
being called?
Is it possible to provide a non-virtual function in a derived class, that hides the virtual function in the base? What signature should the derived member function have so that b->foo()
calls it, and not (b->*&A::foo)()
B::foo()
is virtual. The premise of your question is wrong. – SelfpossessionB::foo()
as virtual" instead of ``B::foo()` isn't virtual") – Leelandvirtual
toB::foo
, I suggest instead to tag onoverride
. – Edgeways...
– Leeland