A Base Class pointer can point to a derived class object. Why is the vice-versa not true?

If I tell you I have a dog, you can safely assume that I have a pet.

If I tell you I have a pet, you don't know if that animal is a dog, it could be a cat or maybe even a giraffe. Without knowing some extra information you can't safely assume I have a dog.

similarly a derived object is a base class object (as it's a sub class), so it can be pointed to by a base class pointer. However, a base class object is not a derived class object so it can't be assigned to a derived class pointer.

(The creaking you will now hear is the analogy stretching)

Suppose you now want to buy me a gift for my pet.

In the first scenario you know it is a dog, you can buy me a leash, everyone is happy.

In the second scenario I haven't told you what my pet is so if you are going to buy me a gift anyway you need to know information I haven't told you (or just guess), you buy me a leash, if it turns out I really did have a dog everyone is happy.

However if I actually had a cat then we now know you made a bad assumption (cast) and have an unhappy cat on a leash (runtime error).

ClassCastException Cat


We have two objects.

class A {
   int a;
};

class B : A {
   int b;
};

Allocate an instance of B. We can interface with that as either an A* or a B*.

Allocate an instance of A. If we were to cast it to a B*, should there be space allocated for the member b?


Uh, because the base class is not a derived class.

When you have a valid pointer to a type, then you are saying that the object pointed to will have certain data in certain locations so that we can find it. If you have a pointer to a derived object, then you are guaranteeing that the pointed-to object contains all of Derived's data members- but when you point to a Base, then it infact doesn't have that and Bad Things Happen™.

However, Derived is guaranteed to have all of the Base data members in the same locations. That's why a pointer to Base can actually point to Derived.

Tags:

C++