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?
Not when using
objas-is by itself, becausebis not a member ofBase.But, IF AND ONLY IF
objis pointing at aDerived(or descendant) object, you can type castobjto aDerived*pointer in order to directly access members ofDerived.Otherwise, another option is to define a
virtualmethod inBasethatDerivedcan override to access its own members as needed. You can then call that method viaobjas-is.No. A
Derivedobject is also a validBaseobject, soobjis simply pointing at theBaseportion of theDerivedobject. 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.