Reputation: 61
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
Upvotes: 0
Views: 132
Reputation: 311126
You forgot to specify the type of the variable (that is to define the object). Write
bool Bullet::active = false;
instead of
Bullet::active = false;
That is at first you have to define the object and only after that you can assign it.
As for the statement you showed
Bullet::active = false;
then it is not a definition of active. It is an assignment statement.
Take into account that the definition should be placed in some module. If you will place it in the header you can get an error that the object is already defined.
Upvotes: 0
Reputation: 98516
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.
Upvotes: 1
Reputation: 16112
static class members need to be defined somewhere, in your case there must be a
bool Bullet::active;
definition in a cpp file of your choice (a file which #includes the class declaration).
You can think of static members as global variables which happen to be in the "namespace" of the class. The class declaration as such doesn't create any objects, not even the static members, it's just, well, a declaration.
Upvotes: 0