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.
The behaviour is undefined. You can only cast
a
toB*
if it is a pointer to aB
.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.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:The memory layout of
B
is: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). Sob
is stored in free space.In short: don't rely on this code to work!
Your code will lead to 2 undefined behaviour:
A
as aB
.b
(this variable does not exist in memory).Here is pontential implementation to use an instance of B as a pointer of A.
@anderas has provided a very good explanation why the behavior is undefined.
Here is a relevant clause from the standard (n4431, emphasis mine):
So, the cast in your code is undefined.
The following would work: