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 13: Making Classes Work 169Why bother with member functions?Why should you bother with member functions? What’s wrong with the goodol’ days:class Savings{public:unsigned accountNumber;float balance;};float deposit(Savings& s, unsigned amount){s.balance += amount;return s.balance;}Here, deposit() implements the “deposit into savings account” function.This functional solution relies on an outside function, deposit(), to implementan activity that savings accounts perform but that Savings lacks. Thisgets the job done, but it does so by breaking the object-oriented (OO) rules.The microwave oven has internal components that it “knows” how to use tocook, defrost, and burn to a crisp. Class data members are similar to theparts of a microwave — the member functions of a class perform cook-likefunctions.When I make nachos, I don’t have to start hooking up the internal componentsof the oven in a certain way to make it work. Nor do I rely on someexternal device to reach into a mess of wiring for me. I want my classes towork the same way my microwave does (and, no, I don’t mean “not verywell”). I want my classes to know how to manipulate their internals withoutoutside intervention.Member functions of Savings such as deposit() can be written as externalfunctions. I can put all of the functions necessary to make a savings accountwork in one place. Microwave ovens can be made to work by soldering andcutting wires. I don’t want my classes or my microwave ovens to work thatway. I want a Savings class that I can use in my banking program withoutconsidering how it might work on the inside.Adding a Member FunctionThere are two aspects to adding a member function to a class: creating themember function and naming it (sounds silly, doesn’t it?).

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

Saved successfully!

Ooh no, something went wrong!