Static Data Member • Single copy exists; shared by all the objects. • Also known as class variables. • Exists and initialized to zero before any object is created. • Within a class, they are declared not defined. • Requires a global definition outside the class. – Re-declaration using scope resolution operator. Thapar University UTA009 2 Example 1. #include<iostream> myClass Common to all the objects 2. using namespace std; a c set() get() 3. class myClass 4. { static int a; int b; 5. public: Object 1 Object 2 Object O 6. static int c; b b … b 7. void set(int i, int j) 8. { a++; b = i; c = j; } 9. void get() 10. { cout << "\nStatic a: " << a << ". Non-static b: " << b << ". Static c: " << c; } 11. }; 12. int myClass :: a = 10; 13. int myClass :: c; Thapar University UTA009 3 Example 14. int main() 15. { 16. cout << "\nPublic Static c: " << myClass :: c; 17. myClass m1, m2; 18. m1.set(1,2); 19. m2.set(3,4); 20. m1.get(); 21. m2.get(); 22. return 0; Output 23. } Public Static c: 0 Static a: 12. Non-static b: 1. Static c: 4 Static a: 12. Non-static b: 3. Static c: 4
Thapar University UTA009 4
Uses • Provide access control of shared resource used by all the objects of a class, e.g. writing a file.
• To keep track of the number of objects of a
particular class type.
• Note:
Virtually eliminates any need for global variables.
Thapar University UTA009 5 Static Member Functions • Can access only other static members of the class. • Do not have a this pointer. • They cannot be declared as const or volatile. • They may not be virtual. • There cannot be static and non-static version of the same function. • Can be called using – An object. – Class name and scope resolution operator.
Thapar University UTA009 6
Example • Objective: Write a program to provide access control to some shared resource. • Example: Create several objects, each of which wants to print a file on a specific printer. Clearly, only one object can be allowed to print a file at a time. In this case, declare a static variable that indicates when the printer is in use and when it is free. Each object then interrogates this variable to get the printer.