in the following code, due to name() being virtual, I would expect that the method of derived struct will be called. Conversely, whats get written out is "A". Why?
#include <iostream>
using namespace std;
struct A {
virtual string name() { return "A"; }
};
struct B : A {
string name() { return "B"; }
};
int main (int argc, char *argv[]) {
B b;
cout << static_cast<A>(b).name() << endl;
return 0;
}
static_cast<A>(b)
creates a temporary variable of typeA
constructed fromb
. So callingname()
indeed invokesA::name()
.In order to observe polymorphic behavior you may do