3 Pointer casting (subclass to superclass)

With our example, let us define a team as follows:

Student *team[3];

This means team is an array of three pointers to objects of the Student class. To be more specific, each pointer in team can point to an object of the class Student or a subclass of Student. This makes it possible to do the following:

team[0] = new Student;
team[1] = new CISStudent;
team[2] = new ArtStudent;

team[0]->getTranscript() invokes Student::getTranscript. In fact, team[1]->getTranscript() and team[2]->getTranscript() all invoke Student::getTranscript. This is hardly surprising because all team[] elements are Student pointers.

Here comes the cool part. team[1]->takeTest() invokes CISStudent::takeTest, while team[2]->takeTest() invokes ArtStudent::takeTest. This is because the takeTest method is virtual. You can say that ``a virtual method is sticky, it sticks to the pointer (to the object)''.

In this example, takeTest is sticky, and each type of students has its own method of taking a test. However, getTranscript is not sticky, so when a subclass pointer is casted to a superclass pointer, the getTranscript method is reverted to that of the superclass.



Subsections
Copyright © 2006-10-05 by Tak Auyeung