-2

I am studying for my finals and there is a topic which is bugging me recently i don't understand why we use static variables or static data members in our code. Can anyone explain it to me how and why we use the static keyword in C++

I have tried looking it up on different sites and i have tried some code, what i don't understand is why am i getting such results.

class myclass {
    public:
    int a,b;
    inline int getVal();
};

inline int myclass :: getVal()
{
    cout<<"Enter the value of a and b\n";
    static int  a = 9; //static keyword used.

    cin>>a>>b;
}
int main()
{
    myclass o1;
    o1.getVal();
    cout<<"\nThe value of a is : "<<o1.a<<"\nThe value of b is : "<<o1.b;
}

the value i am getting for a is 3, no matter what i enter? can anyone explain to me why is that?

Tas
  • 7,023
  • 3
  • 36
  • 51
Free-Man
  • 11
  • 1
  • 2
    If you're studying for your finals, don't you have a book, or access to a library? – molbdnilo Apr 28 '19 at 10:21
  • Hi @Free-Man! Welcome to SO. This is well-known topic and you can find so much information about `static` and it's usage in almost all C++ text books and online tutorials. Furthermore, have a look at this SO question: [The static keyword and its various uses in C++](https://stackoverflow.com/questions/15235526/the-static-keyword-and-its-various-uses-in-c) – Constantinos Glynos Apr 28 '19 at 10:22
  • Your issue has nothing to do with static storage duration and everything to do with lexical scope. Perhaps you've been unable to find an answer because you've been investigating the wrong suspect. Try removing the `static`, and initialising the `a` member in a constructor to various values. – molbdnilo Apr 28 '19 at 10:23
  • Also: always initialise your variables. – molbdnilo Apr 28 '19 at 10:25
  • You have two different variables named `a`: One is a member and the other is a static variable only visible inside `getVal`. You only assign the static variable. – interjay Apr 28 '19 at 10:35

2 Answers2

1

The meaning of static is this: When a variable is declared as static, space for it gets allocated for the lifetime of the program. Even if the function is called multiple times, space for the static variable is allocated only once and the value of variable in the previous call gets carried through the next function call.

Starting point

Bogdan Doicin
  • 2,342
  • 5
  • 25
  • 34
-1

The static keyword means that a variable is bound to a class itself instead of an object of the class. If it is not declared as static it can be changed for each object of the class individually whereas if you change a static variable of a class it is set to the new value for all of its objects.

I hope this helps. If you have any questions feel free to ask.

Edit: as Bogdan Doicin pointed out in another answer static has another meaning in functions. I will leave this up for the other meaning but if you want to accept an answer accept his because it better fits the question.

canislepus
  • 14
  • 3