In this chapter we shall study about:
- Static data members
- Static member functions
- Static Objects
1. Static data members
Below are the properties of static data members:
- “static” is the keyword used to create static data members.
- We want to create static data members, when we want only one copy of that data member to be shared between multiple objects.
- When the first object is created, the value will be initialized to zero.
- Scope is within the class
- Lifetime is till the execution of the program.
- You can initialize the static data member using scope resolution operator.
- You can also access the static variable in main function using scope resolution operator as “ class_name :: static_variable_name”.
Example for static data members:
#include <iostream> using namespace std; class MyClass { public: static int no_of_objects; //default constructor MyClass() { no_of_objects ++; } void get_object_count() { cout<<"The number of objects are = "<<no_of_objects<<endl; } }; int MyClass :: no_of_objects =0; int main(void) { cout<<"The number of objects are = "<<MyClass::no_of_objects<<endl; MyClass obj_1; obj_1.get_object_count(); MyClass obj_2; obj_2.get_object_count(); MyClass obj_3; obj_3.get_object_count(); return 0; }
Output:
The number of objects are = 0 The number of objects are = 1 The number of objects are = 2 The number of objects are = 3
2. Static member functions
Below are the properties of static member functions:
- “static” is the keyword used to declare static member function.
- “this” pointer will not be present in static member functions.
- Static member functions can be accessed without creating an object. It can be called using scope resolution operator. “<class_name>::<static_member_function_name> ().
- Static member function can only access static data members and static member functions.
- You cannot have static and non-static member functions with same name.
Example:
#include <iostream> using namespace std; class MyClass { public: static void myFunc() { cout<<"In myFun function"<<endl; } }; int main(void) { MyClass::myFunc(); return 0; }
Output:
In myFun function
3. Static Objects
#include <iostream> using namespace std; class MyClass { public: void myFunc() { cout<<"In myFun function"<<endl; } }; int main(void) { static MyClass obj; obj.myFunc(); return 0; }
Output:
In myFun function