Hi,

I've confusion with static member variable in c++ class.

Please have a look on following code.
class test
{
public:
static int i;
float j;
};

int test::i = 0;

int main()
{
test *t = new test;

test::i = 100;
cout << "test::i = " << test::i << endl;

t->j = 10.67;
cout << "t->j = " << t->j << endl;

delete t;
t = NULL;

t->i = 200;
cout << "t->i = " << t->i << endl;

return 0;
}


In above code, i've delete class pointer, t and assigned it to NULL;
and on that i'm accessing static member variable (t->i). It is working fine.
My question is why it should not crash, as i'm accessing member variable on null.

Please help.

Thanks & regards,
Amar

It's a static member. Only one instance of the member variable exists in the whole program and all instances of the class access the same variable. Additionally, an instance of the class is not required to access it. It can be accessed "directly" from any scope the "test" identifier is available in.

Observe:

#include <iostream>
using std::cout;
using std::endl;

class test {             //define the test class
 public: 
   static int i;
   float j;
   ~test() { std::cout << "test object deleted..." << endl; }
};                       //end class definition

int test::i = 0;         //initialize the static member

int main() {

  //allocate and initialize 2 test objects
  test *t1 = new test;     //test object 1 't1'
  t1->j = 1.5f;

  test *t2 = new test;     //test object 2 't2'
  t2->j = 4.5f;

  //display the object(s) original state:
  cout << "Showing original values:" << endl;
  cout << "test::i = " << test::i << "\nt1::i = " << t1->i << " t1::j = " << t1->j
    << "\nt2::i = " << t2->i << " t2::j = " << t2->j << endl << endl;

  //modify the static member
  cout << "Changing t1::i to 10..." << endl << endl;
  t1->i = 10;

  //display the object(s) modified state:
  cout << "Revised values:" << endl;
  cout << "test::i = " << test::i << "\nt1::i = " << t1->i << " t1::j = " << t1->j
    << "\nt2::i = " << t2->i << " t2::j = " << t2->j << endl << endl;

  //de-allocate the objects:
  delete t1;
  delete t2;

  //re-display the static member
  cout << "Showing test::i..." << endl;
  cout << "test::i = " << test::i << endl;

  return 0;
}

Note that this is not to say you should be writing code like you have. Even though it works it's a bad idea to write your code like that.

Thanks Fbody.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.