Do you know we can count the number of times a function has been called by defining a variable inside the function only? Yes! We can achieve it using the functionality of the static keyword.
So, in this article, we are going to have a look at the static keyword, what is a Static member function C++, from its declaration to its entire implementation and its types with examples in detail.
Let's begin step by step!
Static Keyword
The static keyword is used to allocate the memory to a variable or function till the lifetime of the program. Didn't understand? Don't worry at the end of this article you will have a clear understanding, of what does it mean?
Syntax:
static data_type variable_name ; static data_type funciton_name ;
The static keyword has different meanings when used with different types. We can use static keywords with:
- Static Variables: Variables in a function, Variables in a class
- Static Members of Class: Class objects and Functions in a class
Static Variables
Let's first start with static variables:
Variables in a function
In this type, we will declare a variable as statically defined inside the function and we will call this function again and again. Even if we call a function multiple times, its value will be initialized only once rather than again and again and we can store the previous state of this variable till the next call of the function.
Let's understand with the help of an example:
// Welcome to Favtutor // C++ program to demonstrate // the use of static // variables in a Function #include<iostream> #include<string> using namespace std; void demo() { // static variable static int count = 0; cout << count << " "; // value is updated and // will be carried to next // function calls count++; } int main() { for (int i=0; i<5; i++) demo(); return 0; }
In this example, the count variable has been declared as static that means, memory for this count variable will be allocated for the lifetime of the program. Therefore, whenever we call a function its previous value will be stored and carried throughout the lifetime of the program.
Even if the function is called multiple times, space for the static variable is allocated only once. This is useful in applications where we have to store the previous state of the function.
Note: As a side note, Java doesn’t allow static local variables in functions.
Static variables in a class
Now, as we know, the static variable is initialized only once. So, even if we create multiple objects of the same class, all objects will share the same static variable rather than having multiple copies of the same static variable. Also because of this reason, static variables can not be initialized using constructors.
Let's understand with the help of an example:
// Welcome to Favtutor // C++ program to demonstrate static // variables inside a class #include<iostream> using namespace std; class Favtutor { public: static int i; Favtutor() { // Do nothing }; }; int main() { Favtutor obj1; Favtutor obj2; obj1.i =2; obj2.i = 3; // prints value of i cout << obj1.i<<" "<<obj2.i; }
Now, as we can see in the above example, we are trying to create multiple copies of the same static variable in obj1 and obj2. But this didn’t happen. We can define the static variable using the class name and scope resolution operator with the variable name outside of the class as shown below:
// Welcome to Favtutor // C++ program to demonstrate static // variables inside a class #include<iostream> using namespace std; class Favtutor { public: static int i; Favtutor() { // Do nothing }; }; int Favtutor::i = 1; int main() { Favtutor obj; // prints value of i cout << obj.i; }
Output:
1
Static Members of Class
Now, we should talk about static class members.
Class objects as static
Till now, we came to know variable can be declared as static using the keyword static used as a prefix, and the memory for that variable is allocated during the lifetime of the program and can be initialized only once. Similarly, objects can be declared static.
First, we will see the C++ program control flow without the static functionality as shown below:
// Welcome to Favtutor // CPP program to illustrate // when not using static keyword #include<iostream> using namespace std; class Favtutor { int i; public: Favtutor() { i = 0; cout << "Inside Constructor\n"; } ~Favtutor() { cout << "Inside Destructor\n"; } }; int main() { int x = 0; if (x==0) { Favtutor obj; } cout << "End of main\n"; }
Output:
Inside Constructor Inside Destructor End of main
In the above example, we created an object obj of class Favtutor inside the if block as shown. So, the scope of the variable "i" will be limited to only if block. So, the first constructor is called and at the time when the control of the program gets out of the if block, the destructor will be called because the scope of "i" or object obj is limited to if block only, and then the last 'cout' will be called.
Now, let's take the same example but using the static keyword as shown below:
// Welcome to favtutor // CPP program to illustrate // class objects as static #include<iostream> using namespace std; class favtutor { int i = 0; public: favtutor() { i = 0; cout << "Inside Constructor\n"; } ~favtutor() { cout << "Inside Destructor\n"; } }; int main() { int x = 0; if (x==0) { static favtutor obj; } cout << "End of main\n"; }
Here, we define the object obj as static. Now what happens is that the scope of this object obj is now outside of that if block too rather than limited too if block as seen previously. So, even if the control flow of the program will get out of the if block, the destructor will be called at the end of the program execution as seen in the output:
Output:
Inside Constructor End of main Inside Destructor
Static functions in a class
Static member functions are allowed to access only the static data members or other static member functions, they can not access the non-static data members or member functions of the class.
We are allowed to invoke a static member function using the object and the ‘.’ operator but it is recommended to invoke the static members using the class name and the scope resolution operator.
By declaring a functioning member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.
Static member functions have a class scope and they do not have access to this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.
As shown in the example below:
// Welcome to Favtutor // C++ program to demonstrate static // member function in a class #include<iostream> using namespace std; class Favtutor { public: // static member function static void printMsg() { cout<<"Welcome to Favtutor!"; } }; // main function int main() { // invoking a static member function Favtutor::printMsg(); }
Output:
Welcome to Favtutor!
Note:
- The name of any static data member and static member function must be different from the name of the containing class.
- The static keyword is only used with the declaration of a static member, inside the class definition, but not with the definition of that static member:
class X { static int n; }; // declaration (uses 'static') int X::n = 1; // definition (does not use 'static')
Conclusion
The static keyword is useful for implementing coroutines in C/C++ or any other application where the previous state of function needs to be stored. So, now you will get a clear understanding of the static keyword and its definition and usage with examples in detail.
Congratulations on getting this far! Now give yourself a pat on the back. Good job!