Static Member Function and Variables in C++

In a C++ programming we can create static function and variable by using the “static” keyword.

Static Variables

 In C++ programming we can create a static variable by placing the “static” keyword before the variable declaration.

Once a variables declared as static, only one copy of that variable is created for the whole class.

static variable
static variable

 When a variable is declared as static, by default it is initialize to zero.

Output

Note: In the above figure we have a two object (object 1 & object 2) we object occupies a separate memory for variable(for ex: for variable 1 , object1 and object2 both will occupy the memory) .

But when a variable declared as a static then only one memory location is occupy for all object.

Static function

In C++ programming we can create a static function by placing the “static” keyword before the function declaration .

A static function can only assess static member variable and member function. 

In a C++ it is also possible to call a  static member function without object.

Static public member function:

Example: WAP to declare public member function and call them from main().

Static function can’t assess normal variable

A static function can only assess static  variable .

A static function can’t access normal function.

If we try to access normal function within the static function then we will get an error.

Output

Static Object

In a C++ programming like a static variable &  function we can also declare a static object.

The object is a composition of one or more member variable of the class.

When we declare a static object by default it initializes all variables of class with zero.

Output