The static keyword is used as a modifier on variables, methods. When a data member is declared as static, only one copy of the data is maintained for all objects of the class. A static member is shared by all objects of the class.
- Static members are often called as class members, such as class variable and class methods or function.
- The static members can be called before the creation of object of class.
- Static block code executes only once, when the class is loaded.
- Static members – static variables and static methods.
Syntax :
1) static variables :
Static data_type variable_name;
2) static method :
static data_type method name()
{
//method body
}
Example :
#include <iostream>
using namespace std;
//class declaration
class staticDemo
{
private:
//static variable declaration
static int sum;
//normal variable declaration
int x;
public:
//Constructor of the class
staticDemo()
{
sum=sum+1;
x=sum;
}
//Static function staticFunction( ) defined with keyword static
static void staticFunction()
{
cout << "\nResult is : " << sum;
}
//Normal member function normalFunctionNumber()
void normalFunctionNumber()
{
cout << "\nNumber is : " << x;
}
};
int staticDemo::sum=0;
//declaration of main method
int main()
{
cout<<"This is how static method and variable work : \n";
//creation of object
staticDemo stat;
//Static function staticFunction() accessed using class name staticDemo and the scope resolution operator ::
staticDemo::staticFunction();
//
staticDemo stat1,stat2,stat3;
staticDemo::staticFunction();
stat.normalFunctionNumber();
//Normal member function accessed using object stat and the dot member access operator.
stat1.normalFunctionNumber();
stat2.normalFunctionNumber();
stat3.normalFunctionNumber();
}
Output :
This is how static method and variable work :
Result is : 1
Result is : 4
Number is : 1
Number is : 2
Number is : 3
Number is : 4
