0

I have a class in which I defined a static integer that I hope will keep track of how many objects of that class get instantiated.

class mob {

public:

mob::mob();
mob::mob(std::string, std::string, int, int, int, int, int);
//some other stuff

private:
//some other stuff
static int mob_count;

};
int mob::mob_count = 0; 

then I define the following constructor:

    mob::mob(string name, string wName, int lowR, int highR, int health, int defense, int reward)
{
    nName = name;
    nWeapon.wName = wName;
    nWeapon.wRange.Rlow = lowR;
    nWeapon.wRange.RHigh = highR;
    nHealth = health;
    nArmor = defense;
    xpReward = reward;
    ++mob_count;
}

So what am I missing? I think i'm doing everything my text book tells me.

I get this when compiling

I hope someone can point my mistakes, thank you very much.

EDIT: @linuxuser27 helped me solve my problem, so basically i just moved the

 int mob::mob_count = 0; 

from the class definition, to the class implementation, like so:

mob.h:

class mob {

public:

mob::mob();
mob::mob(std::string, std::string, int, int, int, int, int);
//some other stuff

private:
//some other stuff
static int mob_count;

};

mob.cpp

int mob::mob_count = 0; 

constructor stays the same.

valiano
  • 16,433
  • 7
  • 64
  • 79

1 Answers1

0

I assume you are declaring your class in a header file (e.g. mob.hpp) and then including the header file in multiple compilation units (i.e. cpp files). Basically this:

main.cpp

#include "mob.hpp" ...

mob.cpp

#include "mob.hpp" ...

Remove int mob::mob_count = 0; from the header file and put it in the mob.cpp.

linuxuser27
  • 7,183
  • 1
  • 26
  • 22
  • Yes i'm including my header files and i know they're properly included because it worked fine before adding this static integer. Should i define the initialization of static int mob_count on mob's constructor then? – Daniel Mateus Mar 25 '17 at 20:45
  • So the issue here is that C++ is normally fine with _declaring_ something multiple times as long as you are consistent. However, it is quite finicky about _defining_ a thing multiple times. In this case, leave the declaration in your class as `private`, but move your definition, `int mob::mob_count = 0;`, to your `mob.cpp` so it will only be defined once. – linuxuser27 Mar 25 '17 at 20:51
  • You should check out this answer: http://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration – linuxuser27 Mar 25 '17 at 20:53