11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

262Part IV: Inheritanceclass GraduateStudent : public Student{};Here, a GraduateStudent inherits all the members of Student. Thus, aGraduateStudent IS_A Student. (The capitalization of IS_A stresses theimportance of this relationship.) Of course, GraduateStudent may also containother members that are unique to a GraduateStudent.Do I Need My Inheritance?Inheritance was introduced into C++ for several reasons. Of course, the majorreason is the capability of expressing the inheritance relationship. (I’ll return tothat in a moment.) A minor reason is to reduce the amount of typing. Supposethat you have a class Student, and you’re asked to add a new class calledGraduateStudent. Inheritance can drastically reduce the number of thingsyou have to put in the class. All you really need in the class GraduateStudentare things that describe the differences between students and graduatestudents.This IS_A-mazingTo make sense of our surroundings, humansbuild extensive taxonomies. Fido is a specialcase of dog, which is a special case of canine,which is a special case of mammal, and so itgoes. This shapes our understanding of theworld.To use another example, a student is a (specialtype of) person. Having said this, I already knowa lot of things about students (American students,anyway). I know they have social secudaydreamabout the opposite sex (the malerity numbers, they watch too much TV, and theyones, anyway). I know all these things becausethese are properties of all people.In C++, we say that the class Student inheritsfrom the class Person. Also, we say thatPerson is a base class of Student, andStudent is a subclass of Person. Finally, wesay that a Student IS_A Person (using allcaps is a common way of expressing thisunique relationship — I didn’t make it up). C++shares this terminology with other objectorientedlanguages.Notice that although Student IS_A Person,the reverse is not true. A Person IS not aStudent. (A statement like this always refersto the general case. It could be that a particularPerson is, in fact, a Student.) A lot of peoplewho are members of class Person are notmembers of class Student. In addition, classStudent has properties it does not share withclass Person. For example, Student has agrade point average, but Person does not.The inheritance property is transitive. For example,if I define a new class GraduateStudentas a subclass of Student, GraduateStudentmust also be Person. It has to be that way:If a GraduateStudent IS_A Student and aStudent IS_A Person, a GraduateStudentIS_A Person.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!