Tuesday, July 28, 2009

Polymorphism in C++?

Does C++ require that pointers be used to use Polymorphism in C++?





Why I ask:


I created a simple class Vehicle which has nothing except a member function called "showType()" which displays "I am a vehicle". I then created a subclass of Vehicle, Car, with a function called "showType()" which displays "I am a car". The function showType() is marked as virtual in the base class.





If I write the following code:


Vehicle test[10] ;


Car c ;


test[0] = c ;


test[0].showType() ;


The output "I am a Vehicle is produced" -- clearly no polymorphism.





However, if I change to using pointers:


Vehicle* test[10] ;


Car c ;


test[0] = %26amp;c ;


test[0]-%26gt;showType() ;





This shows the result I expect -- "I am a car". Does C++ only support Polymorphism with pointers? In some sense this seems to be logical since Polymorphism is a runtime feature, however I was a little disappointed that it couldn't distinguish in the non-pointer case -- I was hoping for a container type effect similar to Java.

Polymorphism in C++?
The difference, Sharpie, between


test[0] = c ;


and


test[0] = %26amp;c ;


is that in the first case you are copying an instance of something to a Vehicle. In that event, all of c that is a Vehicle will be copied to test[0], and test[0] will have none of the Carness. C will remain a Car and test[0] will remain only a Vehicle.


However, %26amp;c is a pointer, so regardless of type it is cast to, it will always be a pointer to an instance of a Car, even if it is cast to a Vehicle pointer.


As a rule of thumb, yes, you will need to deal only with pointers if you are going to make polymorphism work. However, according to the technical definition, a reference is not a pointer, but as far as the machine code is concerned, it is, so this


Vehicle %26amp;v = c;


v.showType();


would also reveal it to be a Car.
Reply:That is the correct behavior in both cases.





You will only see polymorphic behavior with pointers and references.





My java is pretty rusty but I don't recall that it is different in this respect. I suspect you were storing references (whether or not you realized it) in the containers.
Reply:Its supported!!





I also am studying programming and do not know but here:


http://www.google.com/search?hl=en%26amp;q=pol...


No comments:

Post a Comment