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)()
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…