Chapter 18. Static Members: Can Fabric Softener Help?
In This Chapter
Declaring static member data
Defining and using static member functions
Understanding why my static member function can't call my other member functions
By default, data members are allocated on a per-object basis. For example, each person has his or her own name. You can also declare a member to be shared by all objects of a class by declaring that member static. The term static applies to both data members and member functions, although the meaning is slightly different. This chapter describes both types, beginning with static data members.
Defining a Static Member
The programmer can make a data member common to all objects of the class by adding the keyword static
to the declaration. Such members are called static data members. (I would be a little upset if they were called something else.)
Why you need static members
Most properties are properties of the object. Using the well-worn (one might say, threadbare) student example, properties such as name, ID number, and courses are specific to the individual student. However, all students share some properties — for example, the number of students currently enrolled, the highest grade of all students, or a pointer to the first student in a linked list.
It's easy enough to store this type of information in a common, ordinary, garden-variety global variable. For example, you could use a lowly int
variable to keep track of the number of Student
objects. The problem with this ...
Get C++ For Dummies®, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.