Suppose I have a Base class "Computers" and a derived class "Laptops" derived from the "Computers" class.
Now WHAT is the meaning of the following declaration ?? WHEN is it used ?? and HOW is it useful??
Computers C=new Laptops();
Loading
Suppose I have a Base class "Computers" and a derived class "Laptops" derived from the "Computers" class.
Now WHAT is the meaning of the following declaration ?? WHEN is it used ?? and HOW is it useful??
Computers C=new Laptops();
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Sunny SharmaRank #223 · 11.1K reputationPosted May 27, 2013, 12:17 PM EDT
This process is called object slicing. To be precise on that, when a Derived Class object is assigned to Base Class object, the content of derived class, only that belong to Base Class, is copied to Base Class object leaving the specific contents of Derived Class object. Simplifying that, the Base Class object can access only the Base Class members.
Now from the usage point of view, I would say, It's all up to you. For a simple demonstration, take an example of a "Vehicle" Base Class. Suppose the vehicle base class has only a basic property "POWER". Derived Classes could be Cycle, Car, Bus, etc. Derived classes may have specific properties depending on their type like seats, wheels etc. Now, no matter what kind of vehicle they are, they can just drive on the road. All are vehicles. So the base class is a general approach to work with "the group" of those objects. If it's needed we can also cast the vehicle as more specified version like Train otrain = (Train) Car. Suppose you need a new vehicle, given you have a Car with all the properties required for that new vehicle, you might simply prefer casting that Car to new vehicle instead of Instantiating a new vehicle and assigning all the properties.
Hope you get the idea behind the scene :)
Please don't forget to accept this as answer if it helps!
Thanks.
VulpesRank #55 · 29.2K reputationPosted May 27, 2013, 11:50 AM EDT
The drawback, of course, is that you can't access the members which are added by the derived classes themselves using such a variable.
Jeramy Singleton6 reputationPosted May 27, 2013, 4:35 PM EDT
VulpesRank #55 · 29.2K reputationPosted May 28, 2013, 2:01 AM EDT