11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

272Part IV: InheritanceYou might want x.calcTuition() to call Student::calcTuition() when xis a Student but to call GraduateStudent::calcTuition() when x is aGraduateStudent. It would be really cool if C++ were that smart.Normally, the compiler decides which function a call refers to at compiletime. When you click the button to tell the C++ compiler to rebuild your executableprogram, the compiler snoops around in your program to decidewhich function you mean with every call based on the arguments used.In the case described here, the declared type of the argument to fn() is notcompletely descriptive. Although the argument is declared Student, it mayactually be a GraduateStudent. A decision can’t be made until you’re actuallyexecuting the program (this is known as runtime). Only when the functionis actually called can C++ look at the type of the argument and decidewhether it’s a plain old student or a graduate student.The type that you’ve been accustomed to until now is called the declared orcompile-time type. The declared type of x is Student in both cases becausethat’s what the declaration in fn() says. The other kind is the runtime type.In the case of the example function fn(), the runtime type of x is Studentwhen fn() is called with s and GraduateStudent when fn() is called withgs. Aren’t we having fun?The capability of deciding at runtime which of several overloaded memberfunctions to call based on the runtime type is called polymorphism, or latebinding. Deciding which overloaded to call at compile time is called earlybinding because that sounds like the opposite of late binding.Overloading a base class function polymorphically is called overriding thebase class function. This new name is used in order to differentiate this morecomplicated case from the normal overload case.Why You Need PolymorphismPolymorphism is key to the power of object-oriented programming. It’s soimportant that languages that don’t support polymorphism can’t advertisethemselves as OO languages. (I think it’s an FDA regulation — you can’t labela language that doesn’t support OO unless you add a disclaimer from theSurgeon General, or something like that.)Languages that support classes but not polymorphism are called object-basedlanguages.Without polymorphism, inheritance has little meaning. Let me spring yetanother example on you to show why. Suppose that I had written a really fabulousprogram that used some class called, just to pick a name out of the air,

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

Saved successfully!

Ooh no, something went wrong!