Click here to Skip to main content
15,889,867 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
B obj1 = (B)new A();



wats actually happening here ???
Posted
Comments
R. Giskard Reventlov 16-Sep-10 8:18am    
Tough homework question?
AspDotNetDev 16-Sep-10 19:30pm    
An assignment is happening. And you should finish it quickly before it's late and you get an F.

A is a base class of B (Or, B is a sub class of A) here. You can always cast a sub class to a base class. As the object of A is being cast to B here,the obj1 will have the functionality defined within the B class only.

These are the basics of Inheritance and
<br />
Polymorphism
. You may wish to learn these first.
 
Share this answer
 
v2
Comments
Alex@UEA 16-Sep-10 9:17am    
If B is a subclass of A, B may have additional functionality that is not expressed in A. So A may not implement functionality that is expected of an object of type B. So what happens if an object of type A is cast to type B and then receives a B specific call?
An assignment is happening (if A is a subclass of B). Or an exception is being thrown (if B is a subclass of A).

Assuming the former - that A is a subclass of B (and so the cast is valid), you're telling the compiler that 'although I just created an 'A', and so obj1 is really an 'A', when I use obj1, treat it as if it were a 'B'.

This is useful when 'B' declares behaviors and properties common to a family of classes, and when you want to be able to work with any member of that family regardless of what specific member of the family it actually is. As Al-Forooque says, what you're doing is polymorphism.
 
Share this answer
 
This is what we call Explicit cast operation taken place.

In case of operators, there are two types of cast :

1. Implicit
2. Explicit

You can assign a child class object to its base class as it is already defined with objects implicitly.

But using () lets you to override the normal assignment operation and try to cast it to another type. The cast will be possible only when the actual object is capable to cast to the object.

To know about casts, you can have a look into :
http://www.abhisheksur.com/2010/07/operator-overloading-with-implicit-and.htm[^]

:rose:
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900