Search code examples
c++data-structuresobject-lifetime

What is the life time of a C++ data structure object?


Suppose I have have a Car.h which define a class called Car , and I have implementation Car.cpp which implement my class Car, for example my Car.cpp can be :

struct Helper { ... };
Helper helpers[] = { /* init code */  };
Car::Car() {}
char *Car::GetName() { .....}

What is the life time of the helpers array ? Do I need say static Helper helpers[]; ? If I have done some bad practices, please let me know.


Solution

  • Any variable declared/defined in global / namespace scope has a complete life time until the code ends.

    If you want your Helper helpers[]; to be accessible only within Car.cpp then only you should declare it as static; otherwise let it be a global. In other words,

    Helper helpers[];        // accessible everywhere if `extern`ed to the file
    static Helper helpers[];  // accessible only in `Car.cpp`
    

    Edit: As, @andrewdski suggested in comment below; you should make helpers[] as static variable since you are using it within this file; even though Helper is not visible outside. In C++, if 2 entirely different unit has same named global variables then compiler silently create a mess by referring them to the same memory location.