TopClassesSubclasses

Subclasses

The code linked to above 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.


TopClassesSubclasses