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.

274Part IV: Inheritancethat calcTuition() is not the only difference between the two classes. Thechances are not good that I will find all the places that need to be changed.Second, I must edit (read “break”) code that was debugged and working,introducing opportunities for screwing up. Edits can be time-consuming andboring, which usually makes my attention drift. Any one of my edits may bewrong or may not fit in with the existing code. Who knows?Finally, after I’ve finished editing, redebugging, and retesting everything, Inow have two versions to keep track of (unless I can drop support for theoriginal version). This means two sources to edit when bugs are found(perish the thought) and some type of accounting system to keep themstraight.Then what happens when my boss wants yet another class added? (My bossis like that.) Not only do I get to repeat the process, but I’ll have three copiesto keep track of.With polymorphism, there’s a good chance that all I need to do is add thenew subclass and recompile. I may need to modify the base class itself, but atleast it’s all in one place. Modifications to the application code are minimized.At some philosophical level, there’s an even more important reason for polymorphism.Remember how I made nachos in the oven? In this sense, I wasacting as the late binder. The recipe read: Heat the nachos in the oven. Itdidn’t read: If the type of oven is microwave, do this; if the type of oven isconventional, do that; if the type of oven is convection, do this other thing.The recipe (the code) relied on me (the late binder) to decide what the action(member function) heat means when applied to the oven (the particularinstance of class Oven) or any of its variations (subclasses), such as amicrowave oven (Microwave). This is the way people think, and designing alanguage along the lines of the way people think allows the programmingmodel to more accurately describe the real world.How Polymorphism WorksAny given language could support early or late binding upon its whim. Olderlanguages like C tend to support early binding alone. Recent languages likeJava only support late binding. As a fence straddler between the two, C++supports both early and late binding.You may be surprised that the default for C++ is early binding. The reason issimple, if a little dated. First, C++ has to act as much like C as possible bydefault to retain upward compatibility with its predecessor. Second, polymorphismadds a small amount of overhead to each and every function call both

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

Saved successfully!

Ooh no, something went wrong!