2.2 Example: sub class 1

Now, let us define the first sub class as follows:

class Student : public Person
{
    char id[32];
  public:
    const char *getId(void) const;
    void setId(const char *id);
    virtual void takeTest(void);
    void getTranscript(void);
    Student(void);
};

In this example, Student : public Person means that a student ``is a'' person. It also means that as a class, Student inherits all data and function members from Person. In other words, any object of Student class automatically has a name, a gender boolean member, and various methods to get and set the attributes. The word public means that everything in Person should be exposed to Student.

However, not everything is exposed to the Student class. Because name and male are private members, they are not exposed to subclasses. The public methods, on the other hand, are exposed to everyone, including subclasses.

personType, being a protected member, is only visible to the class Person and all its derived classes. It is not visible outside of the inheritance tree rooted at Person. This way, the constructor of Student can set personType to the proper value to indicate an object is a student.

For now, we'll use a generic method to take a test. The meaning of the word virtual cannot be explained before we introduce pointer casting.

Let us define two more subclasses as follows:

class CISStudent : public Student
{
  public:
    virtual void takeTest(void);
    void getTranscript(void);
};

class ArtStudent : public Student
{
  public:
    virtual void takeTest(void);
    void getTranscript(void);
};

Note that both CISStudent and ArtStudent are both subclasses of Student. Although Student has a takeTest method, subclasses of it can define their own takeTest methods. The same applies to getTranscript. However, note that getTranscript is not ``virtual''. The significance of virtual will be explained later.

Also, it is possible for a subclass method to refer to a method of the superclass of the same name. In our example, the implementation of CISStudent::takeTest can be as follows:

void CISStudent::takeTest(void)
{
  Student::takeTest(); // do whatever a regular student does
  // then use additional code to submit the answers online
}

This reference to a (protected or public) method of a superclass works for virtual and non-virtual methods.

Copyright © 2006-10-05 by Tak Auyeung