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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sunny SharmaPosted May 27, 2013, 4:17 PM
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.
VulpesPosted May 28, 2013, 6:01 AM
Jeramy SingletonPosted May 27, 2013, 8:35 PM
VulpesPosted May 27, 2013, 3:50 PM
The drawback, of course, is that you can't access the members which are added by the derived classes themselves using such a variable.