|
|
|
|
|
|
|
Static member variables can be used as counters across instances of the class. Because they are not part of the object, the declaration of static member variables does not allocate memory, and static member variables must be defined and initialized outside the declaration of the class. |
|
|
|
|
|
|
|
|
Static member functions are part of the class in the same way that static member variables are. They can be accessed without a particular object of the class and can be used to access static member data. Static member functions cannot be used to access nonstatic member data because they do not have a this pointer. |
|
|
|
|
|
|
|
|
Because static member functions do not have a this pointer, they also cannot be made const. const in a member function indicates that the this pointer is const. |
|
|
|
|
|
|
|
|
In this hour, you also saw how to delegate functionality to a contained object. Containment is restricted in that the new class does not have access to the protected members of the contained class, and it cannot override the member functions of the contained object. |
|
|
|
|
|
|
|
|
You also saw how to declare both friend functions and friend classes. Friend classes should be used with caution, but they can help you find a middle ground between providing access only to the member methods of a class and making methods and data public. |
|
|
|
|
|
|
|
|
Q Why use static data when you can use global data? |
|
|
|
|
|
|
|
|
A Static data is scoped to the class. It therefore is available only through an object of the classthrough an explicit and full call using the class name if the data are public, or by using a static member function. Static data is typed to the class type, however, and the restricted access and strong typing makes static data safer than global data. |
|
|
|
|
|
|
|
|
Q Why use static member functions when you can use global functions? |
|
|
|
|
|
|
|
|
A Static member functions are scoped to the class, and can be called only by using an object of the class or an explicit full specification (such as ClassName::FunctionName()). |
|
|
|
|
|
|
|
|
Q Why not make all classes friends of all the classes they use? |
|
|
|
|
|
|
|
|
A Making one class a friend of another exposes the implementation details and reduces encapsulation. The ideal is to keep as many of the details of each class as possible hidden from all other classes. |
|
|
|
|
|