Reputation: 1843
class a
{
int var;
}
class b :public a
{
int var2,var3;
}
int main()
{
a *poi;
poi=new b;
//b *poi2;
//poi2=new a;
return 0
}
In above code,i was able to allocate a memory using a derived class type pointing to a base class pointer variable.
i.e, a *poi=new b;
But i was not able to allocate a memory using a a base class type pointing to a derived class pointer.
i.e. b *poi=new a;
Why the following memory allocation is not possible? What is the logic behind it?
Upvotes: 1
Views: 146
Reputation: 3806
That's not about memory allocation but about inheritance.
Fruit* f = new Apple
works well, but
Apple* a = new Fruit
would give you a incomplete apple, or even a banana, so compiler doesn't allow you doing that.
Both pointers have same size, and you could use a unsafe static cast to store a fruit pointer into a apple pointer, but you should avoid doing that
Upvotes: 4
Reputation: 1361
here a *poi;
poi=new b;
is valid because poi
has the reference of var
and the object of b
also has the variable var
because of inheritance. which is a valid reference.
in case of b *poi2;
poi2=new a;
poi2
also can have reference of var2
and var3
but object of a
doesn't contain var2
and var3
. which leads to an invalid reference.
I mean poi2->var2
is a valid statement but there is no var2
if compiler allow poi2=new a;
then poi2->var2
will point to an invalid memory segment.
Upvotes: 1
Reputation: 110658
This doesn't really have anything to do with the memory allocation. It is simply that the first conversion is a valid implicit conversion (from derived class pointer to base pointer), but the second is not (from base class pointer to derived pointer):
§4.10/3 [conv.ptr] A prvalue of type “pointer to cv D”, where D is a class type, can be converted to a prvalue of type “pointer to cv B”, where B is a base class (Clause 10) of D.
The reason for this is that polymorphism represents an is-a relationship. A b
is an a
, but an a
is not a b
. Therefore, you can have an a
pointer pointing at a b
, because the object it's pointing at is a valid a
object. However, you can't have a b
pointer pointing at an a
, because an a
object is not necessarily a valid b
object.
Upvotes: 2