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.

Chapter 21: Examining Virtual Member Functions: Are They for Real? 273Student. After months of design, coding, and testing, I release this applicationto rave reviews from colleagues and critics alike. (There’s even talk of startinga new Nobel Prize category for software, but I modestly brush such talk aside.)Time passes and my boss asks me to add to this program the capabilityof handling graduate students who are similar but not identical to normalstudents. (The graduate students probably claim that they’re not similarat all.) Now, my boss doesn’t know or care that deep within the program,someFunction() calls the member function calcTuition(). (There’s a lotthat he doesn’t know or care about, by the way, and that’s a good thing if youask me.)void someFunction(Student& s){// ...whatever it might do...s.calcTuition();// ...continues on...}If C++ didn’t support late binding, I would need to edit someFunction() tosomething like the following to add class GraduateStudent:#define STUDENT 1#define GRADUATESTUDENT 2void someFunction(Student& s){// ...whatever it might do...// add some member type that indicates// the actual type of the objectswitch (s.type){case STUDENT:s.Student::calcTuition();break;}case GRADUATESTUDENT:s.GraduateStudent::calcTuition();break;}// ...continues on...I would have to add the variable type to the class. I would then add theassignment type = STUDENT to the constructor for Student and type =GRADUATESTUDENT to the constructor for GraduateStudent. The value oftype would then indicate the runtime type of s. I would then add the testshown in the preceding code snippet to every place where an overriddenmember function is called.That doesn’t seem so bad, except for three things. First, this is only one function.Suppose that calcTuition() is called from a lot of places and suppose

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

Saved successfully!

Ooh no, something went wrong!