I came across some dodgy code recently. But the behavior left me a bit dumbfounded. The following is a simplification of the problem (basically the virtual keyword is missing, making it non-polymorphic). Why/how is it printing "C::foo called, i: 5"?
How is the object in memory even able to have 'i' in it? I tried C++03 and C++11.
#include <iostream>
using namespace std;
class P
{
public:
void foo()
{
cout << "P::foo called" << endl;
}
};
class C : public P
{
public:
void foo()
{
i = 5;
cout << "C::foo called, i: " << i << endl;
}
int i;
};
int main()
{
C* c = static_cast<C*>(new P());
c->foo();
}