Thursday, July 30, 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++?
C++ always uses pointers to work with polymorphism and other OOP subjects.

rose

No comments:

Post a Comment