class A
{
public:
int a;
};
class B:public A
{
public:
int b;
void foo()
{
b=a*a;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
A * a=new A;
a->a=10;
((B*)a)->foo();
cout<<((B*)a)->b;
}
It's working for b=100, but I dont know by which rules it works. Where is b stored? I just don't know how its called to google it.
Basically, what is happening here is undefined behaviour. It doesn't have a special name; most likely it is called a programming mistake. The memory layout of your class A is:
int a;
The memory layout of B is:
int a;
int b;
So in your case, you only allocate space for a but you are lucky that the space immediately after it is free (so that no other information is overwritten) and that it doesn't border on unallocated space (otherwise, a fault might occur when trying to write to an unallocated page). So b is stored in free space.
In short: don't rely on this code to work!
The behaviour is undefined. You can only cast a to B* if it is a pointer to a B.
Don't do this.
You couldn't even write A* a = new B; followed by (dynamic_cast<B*>(a))->foo(); since the classes are not polymorphic types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With