When we declare the static keyword with variables. Then only one copy of that variable will exist and all the object of the class will share the static variable. Static variables are also called as class variables.
The main difference between static and normal variable is that normal variable is only accessed by the object but static keyword can be accessed by class and object both. Static is used for memory saving. For a normal variable, the output is garbage and for static variable output is zero.
The static variable needs only one type of initialization and value is override but normal variable needs many types of initialization.
- A simple program to print the default value of the static variable by object and class both.
#include<iostream.h> #include<conio.h> class A { public: int x1; static int x2; }; int A::x2; void main() { A a1; clrscr(); cout << a1.x1 << "\t" << a1.x2 << endl; //we can call static variable by object also cout << a1.x1 << "\t" << A::x2; //A::x2-> we can call static variable by class also getch(); }
2. Program to understand one type of initialization by static variables.
#include<iostream.h> #include<conio.h> class A { int x1; static int x2; public: A() { x1=0; x2=0; } void show() { x1++; x2++; cout << x1 << "\t" << x2 << endl; } }; int A::x2; void main() { A a1,a2,a3; clrscr(); a1.show(); a2.show(); a3.show(); getch(); } Output: 1 1 1 2 1 3