#include <cstdio>
#include <cstring>
class A
{
public:
virtual void foo()
{
puts("A");
}
};
class B : public A
{
public:
void foo()
{
puts("B");
}
};
int main()
{
A a;
B b;
memcpy(&a, &b, sizeof (b));
(&a)->foo();
}
#include <cstdio> #include <cstring> class A { public: virtual void foo() { puts(A); }
Share
You are not supposed to mess with non-POD types like that. In particular, the C++ standard says that
memcpying non-PODs results in undefined behavior, which, in your case, shows as continuing to seeaas being of typeA.In your particular case, the compiler “knows” that the both the “static type” and the “dynamic type” of
aisA(since its type can’t “legally” change – your trick is illegal), so no virtual dispatch is performed, buta.foo()is called directly (and your trick of overwriting the vptr thus has no effect).