Understanding variants of Static keyword in C++ With Examples

Hello, folks! Today we will be unveiling another important aspect in the series of our C++ tutorials: Variants of static keyword in C++.


What does static keyword actually mean?

The static keyword in C++ makes any variable, object or function a constant one. That means, only one copy of that particular variable or function would be created and will be accessed by all the instances of the class.

Thus, it would help the programmers assist and manage the memory in a better manner because only a single copy of the static variables/functions reside every time an object calls for it.


Variant 1: Static data members

If any data member or variable in C++ is declared as static, it acts like a class variable. Moreover, only one copy of the variable is available for the class objects to access.

The memory for the static variables get allocated only once, and further all the function which calls to the variable will available by the single copy of the variable. So, no instance copy of static variable is created.

Syntax: Static variable in a member function

Syntax: Static variable within a Class

Example 1: Static variable within a member function

In the above example, we have done manipulations on a static and local variable to understand the difference between their functioning.

When we call the count_static() function, the value is once initialized and creates a single instance of the variable. When the main function encounters the count_static() function, the variable’s value travels through the function.

On the other hand, when we call the count_local() function two times in a loop, the variable will be initialized every time. Thus, the value of local variable remains 1.

Output:

Example 2: Static variable in a class

In the above snippet of code, we have used a static variable within a class. We need to initialize the static variable outside the class, else an exception will be raised.

Further, we can access the value of the static variable using the class name. Thus, we no need to create an object for the same.

Output:


Variant 2: Static function in C++

Static member functions work with static data values and thus cannot access any non-static variables of the class.

Syntax: Static function definition

Syntax: Static Function call

Example:

Output:


Important points regarding static member function

  • Static member functions cannot be overloaded
  • Any static member function cannot be virtual
  • Static functions do not operate with this pointer

Conclusion

Thus, in this article, we have understood the working and variants of static keyword in C++.


References

By admin

Leave a Reply

%d bloggers like this: