How can we store object of derived type into pointers of base type?

81 views Asked by At

I am having difficulty in understanding how we can store objects of derived type into pointer of base type.

class Base
{
    int a;    // An object of A would be of 4 bytes
};

class Derived : public Base
{
    int b;    //This makes Derived of 8 bytes
};

int main()
{
    Base* obj = new Derived();    // Is this consistent? I am trying to store objects of Derived type into memory meant for Base type
 
    delete obj;

    return 0;
}

I see this format being used extensively for achieving run-time polymorphism. I am just wondering if there is a way to access non-inherited data members (b in this case) of Derived object using obj.

Does doing Base* obj = new Derived(); result in object slicing? If so, why is this model prevalent for achieving polymorphism?

1

There are 1 answers

3
Remy Lebeau On

I am just wondering if there is a way to access non-inherited data members (b in this case) of Derived object using obj.

Not when using obj as-is by itself, because b is not a member of Base.

But, IF AND ONLY IF obj is pointing at a Derived (or descendant) object, you can type cast obj to a Derived* pointer in order to directly access members of Derived.

Otherwise, another option is to define a virtual method in Base that Derived can override to access its own members as needed. You can then call that method via obj as-is.

Does doing Base* obj = new Derived(); result in object slicing?

No. A Derived object is also a valid Base object, so obj is simply pointing at the Base portion of the Derived object. Object slicing occurs when you assign an instance of a derived class to an instance of a base class, in which case only the base portion can be assigned. But assigning a pointer to another pointer does not assign the objects that they are pointing at.