Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set derived class field by converting base class pointer

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.

like image 599
tambel Avatar asked Jun 25 '26 05:06

tambel


2 Answers

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!

like image 167
anderas Avatar answered Jun 27 '26 19:06

anderas


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.

like image 21
Bathsheba Avatar answered Jun 27 '26 18:06

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!