Search code examples
c++classmembers

Using a static member variable


Hello in my class Bullet I declare active as false when the bullet isn't active and true when it is. In my other class that isn't connected to my Bullet class in any way I want to use the bool member active and change it, how can I do that?

Im getting the error

Error 18 error LNK2001: unresolved external symbol "public: static bool Bullet::active" (?active@Bullet@@2_NA) C:\Skolarbete\Programmering i C++\ProjectTemplate\ProjectTemplate\Alienrow.obj ProjectTemplate

Declaration: static bool active;

When I use it: Bullet::active = false;

Im quite new too C++ so don't hate! Appreciate all the help I can get :D


Solution

  • A static variable inside a class is actually an external declaration. You still need the variable definition. This is similar to C external variables.

    So in the .h file:

    class Bullet
    {
    public:
        static bool active;
    };
    

    and in the .cpp file, at global scope:

    bool Bullet::active = false;
    

    The lack of the variable definition (not declaration) is deduced because your error message actually comes from the linker, not the compiler.