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.

Chapter 19: Static Members: Can Fabric Softener Help? 253“Well then,” you ask, “if the space for noOfStudents is not allocated in any ofthe objects of class Student, where is it allocated?” The answer is, “It isn’t.”You have to specifically allocate space for it, as follows:int Student::noOfStudents = 0;This somewhat peculiar-looking syntax allocates space for the static datamember and initializes it to zero. Static data members must be global — astatic variable cannot be local to a function.The name of the class is required for any member when it appears outside itsclass boundaries.This business of allocating space manually is somewhat confusing until youconsider that class definitions are designed to go into files that are includedby multiple source code modules. C++ has to know in which of those .cppsource files to allocate space for the static variable. This is not a problemwith non-static variables because space is allocated in each and every objectcreated.Referencing static data membersThe access rules for static members are the same as the access rules fornormal members. From within the class, static members are referenced likeany other class member. Public static members can be referenced from outsidethe class, whereas well-protected static members can’t. Both types ofreference are shown in the following code snippet:class Student{public:Student(){noOfStudents++; // reference from inside the class// ...other stuff...}};static int noOfStudents;// ...other stuff like before...void fn(Student& s1, Student& s2){// reference public staticcout

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

Saved successfully!

Ooh no, something went wrong!