Hemant Bhargava
Hemant Bhargava

Reputation: 3585

Difference between static data member and global variable

Variations of this question might have been asked earlier as well. This question is about static data member vs global variable not static variable vs global variable.

All of us know what static data member and global variables do. How compilers link them, where they get mapped in memory layout, their default values etc. When I think about them I do not have a clear picture of the possible scenarios where we should use static data member instead of global variable.

I thought of one use case where you want to count the number of objects created for a class. You make one static data member and increase in the ctor whenever you create an new object. But at same thought, we could also do the same thing, counting of the created objects, with the global variable as well.

So, it is not clear to me till now that what are the use cases of using static data member vs global variable?

Upvotes: 1

Views: 1908

Answers (1)

Jarod42
Jarod42

Reputation: 217085

They are in different scopes:

  • The static data member can have visibility restriction public/protected/private.
  • The global variable can be modified without restriction
  • The static (global) variable can only be modified in file scope.

Upvotes: 4

Related Questions