Search code examples
variablesglobal-variables

Difference between a "member variable" or "field" and a "global variable"


What is the difference between a member variable or field and a global variable?Is the concept same ?


Solution

  • A member variable is declared within the scope of a class. Unless it’s static, there will be a different copy of the variable for every object of that class.

    A global variable is declared outside the scope of any class and can be used from any function. There’s only one copy of it in the program.

    Note that mainstream object-oriented languages distinguish between a global variable (which is declared outside the scope of any class or function) and a static local variable or class member. However, all the problems with global variables apply equally to mutable public data members that are accessible from anywhere in the program. For most purposes, you can think of these as the same thing.

    Example Code

    #include <iostream>
    
    using std::cout;
    using std::endl;
    
    const int global_var = 1;   // The definition of the global variable.
    
    struct example_t {
      public:
    
      static int static_member_var; // A static member variable.
      const static int const_static_member_var; // These are just declarations.
    
      int member_var;                   // A non-static member variable.
      // Every object of this type will have its own member_var, while all
      // objects of this type will share their static members.
    };
    
    int example_t::static_member_var = 0;
    const int example_t::const_static_member_var = global_var;
    // We can use global_var here.  Both of these exist only once in the
    // program, and must have one definition.  Outside the scope where we
    // declared these, we must give their scope to refer to them.
    
    int main(void)
    {
      example_t a, b;   // Two different example_t structs.
    
      a.member_var = 2;
      b.member_var = 3; // These are different.
    
      a.static_member_var = 5;
      // This is another way to refer to it.  Because b has the same variable, it
      // changes it for both.
    
      // We can use global_var from main(), too.
      cout << "global_var is " << global_var
           << ", example_t::const_static_member_var is " << example_t::const_static_member_var
           << ", b.static_member_var is " << b.static_member_var
           << ", a.member_var is " << a.member_var
           << " and b.member_var is " << b.member_var
           << "."  << endl;
    
      return 0;
    }