Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

A Base Class pointer can point to a derived class object. Why is the vice-versa not true without casting? Logically a base class would not have enough information of the derived class but a derived class should have the information of the base class as well. I am missing some basics here.

like image 764
Zuzu Avatar asked Feb 08 '11 19:02

Zuzu


People also ask

Why a base class pointer can point to its derived class object but a derived class pointer Cannot point to its base class object?

Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.

What happens when a base class pointer points to a derived class object?

A pointer to derived class is a pointer of base class pointing to derived class, but it will hold its aspect. This pointer of base class will be able to temper functions and variables of its own class and can still point to derived class object.

Is derived class pointer Cannot point to base class?

Answer:b. Derived class pointer cannot point to base class.

How the base class reference can point to derived class object what are its advantages?

Although C++ permits a base pointer to point to any object derived from that base, The pointer cannot be directly used to access all the members of the derived class we may have to use another pointer declared as a pointer to the derived type. A derived class is a class that takes some properties from its base class.


1 Answers

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

like image 61
jk. Avatar answered Sep 19 '22 04:09

jk.