What is the difference between a member variable and a local variable?

What is the difference between a member variable and a local variable?

Are they the same?


A local variable is the variable you declare in a function.

A member variable is the variable you declare in a class definiton.


A member variable is a member of a type and belongs to that type's state. A local variable is not a member of a type and represents local storage rather than the state of an instance of a given type.

This is all very abstract, however. Here is a C# example:

class Program
{
    static void Main()
    {
        // This is a local variable. Its lifespan
        // is determined by lexical scope.
        Foo foo;
    }
}

class Foo
{
    // This is a member variable - a new instance
    // of this variable will be created for each 
    // new instance of Foo.  The lifespan of this
    // variable is equal to the lifespan of "this"
    // instance of Foo.
    int bar;
}