Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to use extern variable in classes?

Tags:

c++

c++11

extern

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?

like image 270
nilcit Avatar asked Oct 18 '22 00:10

nilcit


1 Answers

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

like image 140
krzaq Avatar answered Nov 15 '22 05:11

krzaq