nilcit nilcit - 1 year ago 72
C++ Question

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 {
extern string A;

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

Answer Source

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 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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download