nilcit
nilcit

Reputation: 483

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?

Upvotes: 6

Views: 6060

Answers (1)

krzaq
krzaq

Reputation: 16421

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

Upvotes: 3

Related Questions