Ad Code

Static Variables

Static variable belongs to the class and not to the object; it is initialized only once;  Then what is the practical utility of static variable; kindly give any example with code to understand the logic better?

Static variable belongs to the class and not to the object; it is initialized only once;  Then what is the practical utility of static variable; kindly give any example with code to understand the logic better?

// static1.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
void showstat( int curr ) {
   static int nStatic;    // Value of nStatic is retained
                          // between each function call
   nStatic += curr;
   cout << "nStatic is " << nStatic << endl;
}

int main() {
   for ( int i = 0; i < 5; i++ )
      showstat( i );
}
 
nStatic is 0
nStatic is 1
nStatic is 3
nStatic is 6
nStatic is 10

The following example shows the use of static in a class.
 
// static2.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
class CMyClass {
public:
   static int m_i;
};

int CMyClass::m_i = 0;
CMyClass myObject1;
CMyClass myObject2;

int main() {
   cout << myObject1.m_i << endl;
   cout << myObject2.m_i << endl;

   myObject1.m_i = 1;
   cout << myObject1.m_i << endl;
   cout << myObject2.m_i << endl;

   myObject2.m_i = 2;
   cout << myObject1.m_i << endl;
   cout << myObject2.m_i << endl;

   CMyClass::m_i = 3;
   cout << myObject1.m_i << endl;
   cout << myObject2.m_i << endl;
}
 
0
0
1
1
2
2
3
3 
Reactions

Post a Comment

0 Comments