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 22: Factoring Classes 289isn’t necessarily true, but assume that it is.) To express the common write()property, introduce the class HWVGA to implement the write() function (alongwith any other properties that all HWVGA have in common). Don’t overridethe member function initialize(), however, because the different HWVGAsdo not have this property in common.Therefore, although the function write() has been overridden, the classHWVGA is still abstract because the initialize() function has yet to beoverridden.Because ThreedVGA inherits from HWVGA, it has to override only the one missingmember function, initialize(), to complete the definition of Displayadapter. The function fn() is therefore free to instance and use a ThreedVGAobject.Overriding the last pure virtual function with a normal member functionmakes the class complete (that is, non-abstract). Only non-abstract classescan be instanced with an object.Passing abstract classesBecause you can’t instance an abstract class, it may sound odd that it’s possibleto declare a pointer or a reference to an abstract class. With polymorphism,however, this isn’t as crazy as it sounds. Consider the following codesnippet:void fn(Account *pAccount); // this is legalvoid otherFn( ){Savings s;Checking c;}// this is legitimate because Savings IS_A Accountfn(&s);// same herefn(&c);Here, pAccount is declared as a pointer to an Account. However, it’s understoodthat when the function is called, it will be passed the address of somenon-abstract subclass object such as Savings or Checking.All objects received by fn() will be of either class Savings or class Checking(or some future non-abstract subclass of Account). The function is assuredthat you will never pass an actual object of class Account because you couldnever create one to pass in the first place.

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

Saved successfully!

Ooh no, something went wrong!