Search code examples
c++externstorage-class-specifier

C++ extern storage class life-span


I am a C++ newbie and come from a Java background. I would like to confirm the following:

I am reading C++ by dissection by Ira Pohl and the book states that the life-span for a file/extern variable/function is the duration of the program (which makes sense because the variable is not declared in a class).

What I want to know; is that also the case for a variable declared in a class? If not, if a variable is declared in a class does that make the variable use the auto storage class?

Thanks.


Solution

  • A member variable in a class has a life-span corresponding to the life-span of the class's instances, unless declared static.

    struct Foo {
        int x;
        static int y;
    };
    

    This Foo, and therefore its x, has program life-span:

    static Foo foo;
    

    This one is auto:

    int main() { Foo foo; }
    

    This one is dynamically allocated and lives until the Foo is delete'd:

    int main() { Foo *foo = new Foo; }
    

    In each case, the y has program life-span.