Search code examples
c++c++11extern

Possible to use extern variable in classes?


In C++, is it possible to mark a class member variable as extern?

Can I have

class Foo {
    public:
        extern string A;
};

where the string A is defined in another header file that I include?


Solution

  • If I understand your question and comment correctly, you're looking for static data members

    Declare the field as static:

    // with_static.hpp
    struct with_static
    {
        static vector<string> static_vector;
    };
    

    Define it in one TU (±.cpp file) only:

    // with_static.cpp
    vector<string> with_static::static_vector{"World"};
    

    Then you can use it. Please note that you can use class::field and object.field notation and they all refer to the same object:

    with_static::static_vector.push_back("World");
    
    with_static foo, bar;
    foo.static_vector[0] = "Hello";
    
    cout << bar.static_vector[0] << ", " << with_static::static_vector[1] << endl;
    

    The above should print Hello, World

    live demo