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?