mardi 19 mars 2019

Why is the initialization value of derived class member not lost when we cast it to a base pointer?

In the following code as you can see, I was expecting the initialization value of b of class B to be lost since I assigned it to a base pointer A which doesn't have any member b. But it seems to be stored somewhere inside and I still get value of b as 30 in last line. This behavior was unexpected, can someone how is this managed in the memory? Does it mean that when we are allocating derived class members all the members are there in memory and it's accessibility depends if base class pointer has access to that member or not. If someone can provide more insight into the underlying behavior.

include

using namespace std;

class A {
public:
    A(): a(5) {}
    A(int val): a(val) {}
    int a;
    virtual void f() {}
};

class B: public A {
public:
    B(): a(5), b(10) {}
    B(int val1, int val2): a(val1), b(val2) {}
    int a;
    int b;
    virtual void f() {
        cout<<"Dummy";
    }
};

int main(int argc, char **argv)
{
    A *a = new B(20, 30);
    cout<<"a->a: "<<a->a<<endl;
    B *b = dynamic_cast<B*>(a);
    cout<<"b->a: "<<b->a<<" | b->b: "<<b->b;
    return 0;
}

**

  • Output

**:

a->a: 5 b->a: 20 | b->b: 30Time elapsed: 000:00:265 Press any key to continue

Aucun commentaire:

Enregistrer un commentaire