In this chapter we shall study about:
1. Static data members
2. Static member functions
3. Static Objects
1. Static data members
Below are the properties of static data members:
1. “static” is the keyword used to create static data members.
2. We want to create static data members, when we want only one copy of that data member to be shared between multiple objects.
3. When the first object is created, the value will be initialized to zero.
4. Scope is within the class
5. Lifetime is till the execution of the program.
6. You can initialize the static data member using scope resolution operator.
7. 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:
1. “static” is the keyword used to declare static member function.
2. “this” pointer will not be present in static member functions.
3. Static member functions can be accessed without creating an object. It can be called using scope resolution operator. “<class_name>::<static_member_function_name> ().
4. Static member function can only access static data members and static member functions.
5. 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