-5

I was reading c++ code. I saw a static variable has been used as a counter and it has been initialized in the constructor as below :

 class Order{
 int Number;

public:
    Order(){
     int static i=0;
     Number=++i;
     }

   int getNumber(){
      return Number;
   }
    .
    .

So if we instantiate the "Order" class as below :

    Order *o1 = new Order();
    o1.getNumber();
    Order *o2 = new Order();
    o2.getNumber();
    Order *o3 = new Order();
    o3.getNumber();
    //Result :  1 ,2 ,3 

I am wondering how the static variable work in this case. Because each time we instantiate the Order class, actually we are setting int static i=0; so I expect a result like this :

1,1,1

but it seems the process behind static variables is different! So, what is going on behind this static variable and how it works?

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Amir Jalilifard
  • 2,027
  • 5
  • 26
  • 38
  • 3
    Take a look here http://stackoverflow.com/questions/15235526/the-static-keyword-and-its-various-uses-in-c – OMGtechy Apr 21 '15 at 16:56

1 Answers1

3

A static class variable has a single instance across all instances of that class. With standard variables each instance of a class creates an instance of that variable, but with a static variable they all share the same instance. If you were to print the memory address for static int i you'd see that regardless of which Order you were using, that the memory address would be the same.

Someone already mentioned this in a comment, but in case others miss it, read up on static in C++: The static keyword and its various uses in C++

Your question was likely downvoted because you could've read about the static keyword and its use very easily by searching for it instead of asking a question.

Community
  • 1
  • 1
Nic Foster
  • 2,864
  • 1
  • 27
  • 45