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 19: Static Members: Can Fabric Softener Help? 255to evaluate the expression. This is true even if nextStudent() should do otherthings, such as wash windows or shine your shoes. None of those things willbe done. Although the example is obscure, it does happen. That’s what youget for trying to cram too much stuff into one expression.Uses for static data membersStatic data members have umpteen uses, but let me touch on a few here.First, you can use static members to keep count of the number of objectsfloating about. In the Student class, for example, the count is initialized tozero, the constructor increments it, and the destructor decrements it. At anygiven instant, the static member contains the count of the number of existingStudent objects. Remember, however, that this count reflects the number ofStudent objects (including any temporaries) and not necessarily the numberof students.A closely related use for a static member is as a flag to indicate whether aparticular action has occurred. For example, a class Radio may need to initializehardware before sending the first tune command but not before subsequenttunes. A flag indicating that this is the first tune is just the ticket. Thisincludes flagging when an error has occurred.Another common use is to provide space for the pointer to the first memberof a list — the so-called head pointer (see Chapter 14 if this doesn’t soundfamiliar). Static members can allocate bits of common data that all objects inall functions share (overuse of this common memory is a really bad ideabecause doing so makes tracking errors difficult).Declaring Static Member FunctionsMember functions can be declared static as well. Static member functions areuseful when you want to associate an action to a class but you don’t need toassociate that action with a particular object. For example, the member functionDuck::fly() is associated with a particular duck, whereas the rathermore drastic member function Duck::goExtinct() is not.Like static data members, static member functions are associated with aclass and not with a particular object of that class. This means that, like a referenceto a static data member, a reference to a static member function doesnot require an object. If an object is present, only its type is used.Thus, both calls to the static member function number() in the followingexample are legal. This brings us to our first static program — I mean ourfirst program using static members — CallStaticMember:

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

Saved successfully!

Ooh no, something went wrong!