How to Use a Subclass in C++ - dummies

How to Use a Subclass in C++

By Stephen R. Davis

This example C++ program demonstrates the creation and use of two objects, one of class Student and a second of a subclass GraduateStudent. The output of this program is as follows:

Constructing student Cy N Sense
Constructing student Matt Madox
Constructing graduate student Matt Madox
Adding grade to Cy N Sense
Adding grade to Matt Madox
Matt's qualifier grade = 1.5
Press Enter to continue...

The class Student has been defined in the conventional fashion. The class GraduateStudent is a bit different, however. The colon followed by the phrase public Student at the beginning of the class definition declares GraduateStudent to be a subclass of Student.

The appearance of the keyword public implies that there is probably protected inheritance as well. All right, it’s true, but protected inheritance is rarely used.

Programmers love inventing new terms or giving new meaning to existing terms. Heck, programmers even invent new terms and then give them a second meaning. Here is a set of equivalent expressions that describes the same relationship:

  • GraduateStudent is a subclass of Student.

  • Student is the base class or is the parent class of GraduateStudent.

  • GraduateStudent inherits or is derived from Student.

  • GraduateStudent extends Student.

As a subclass of Student, GraduateStudent inherits all its members. For example, a GraduateStudent has a name even though that member is declared up in the base class. However, a subclass can add its own members, for example qualifierGrade. After all, gs quite literally IS_A Student plus a little bit more.

The main() function declares two objects, llu of type Student and gs of type GraduateStudent. It then proceeds to access the addCourse() member function for both types of students. main() then accesses the qualifier() function that is only a member of the subclass.