Translating Java classes into C++TopMore call-by-referenceSubclasses

Subclasses

The code Point in the previous lecture also includes a class ColorPoint, which is intended to be a subclass of Point. The declaration is a bit different than Java:

    class ColorPoint : public Point{
       ...
    }

This indicates that ColorPoint is publically known to be a subclass of Point, and hence may be treated as a subclass. (Private inheritance is also possible in C++.)

Notice that some of the methods are declared to be virtual. These are the methods that can be dispatched dynamically. I.e., the code actually executed when a message is sent will be determined by the run-time value of the receiver rather than the static type of the receiver. Thus, because translate is virtual, if we write:

    ColorPoint cp;
    Point pt = cp;
    pt.translate(2,3);

then because pt represents a color point at run-time, the translate method for ColorPoint will be executed above. Notice that destructors should always be virtual. Also notice that "virtual" is added in the ".h" file but not the ".cpp". Also default parameters go in the ".h" but not the ".cpp" file. Note, however, that "const" declarations must appear in both places.

The sample code in TestPoints.cpp. Illustrates the importance of using pointers when you wish to do true OO programming. In the example, if p is of type Point and cp is of type ColorPoint, then p = cp results in truncating the object in cp so that only the object instance variables are kept, and the Point methods are used. On the other hand if q if of type pointer to Point and cq is of type pointer to ColorPoint, then q = cq retains the colorpoint features and q -> translate(2,3) results in executing the colorpoint translate method even through q's static type is pointer to Point.


Translating Java classes into C++TopMore call-by-referenceSubclasses