Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and why would you upcast an object?

This is considered upcasting correct?

Derived d = new Derived();
Base b = d; // Always OK.

Why would someone upcast? When? Is it because we must turn the object into the base class so it does not have the functionality of the derived class?

How does this code look in memory? Derived class instantiates and memory is created for that object. Then a base class object is made that references d now.

like image 956
RoR Avatar asked Jan 11 '11 09:01

RoR


People also ask

Why do we Upcast?

Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature. Instead of all the members, we can access some specified members of the child class. For instance, we can access the overridden methods.

Why is downcasting needed?

Downcasting is useful when the type of the value referenced by the Parent variable is known and often is used when passing a value as a parameter. In the below example, the method objectToString takes an Object parameter which is assumed to be of type String.

What is the reason to use Upcasting and downcasting?

Why we need Upcasting and Downcasting? In Java, we rarely use Upcasting. We use it when we need to develop a code that deals with only the parent class. Downcasting is used when we need to develop a code that accesses behaviors of the child class.

Why do we need Upcasting in C++?

Upcasting is converting a derived-class reference or pointer to a base-class. In other words, upcasting allows us to treat a derived type as though it were its base type. It is always allowed for public inheritance, without an explicit type cast.


1 Answers

I think you might be a bit confused about what the upcast does. The upcast does not disable the functionality of the derived object, nor does it create a new Base object. Rather, it just takes a more limited view of the object you upcasted. Through the base class reference, you can access only those methods declared in Base, but if any of those methods are overridden in the derived class, invoking them through the base reference will still call the derived version.

As for when you'd want to do this, it's uncommon to see people upcast for no particular reason. After all, that limits what you can do to the object. However, as other posters have pointed out, it's common to implicitly upcast when passing an object into a function or returning an object from a function. In those cases, the upcast allows function authors to either take in a parameter with the weakest set of requirements necessary to get the job done, or to return an object from a function that exhibits some set of behaviors without necessarily revealing the full type of the object.

like image 164
templatetypedef Avatar answered Oct 18 '22 10:10

templatetypedef