1

i have encountered a problem that is i have defined a static member variable inside a class with access specifier being private but whenever a constructor is called corresponding an object the compiler displays an error "undefined reference to MyObject::count" here is my class member variable declaration

class MyObject
{ private:
        static int count;
  public:
      MyObject()
         {
           count=0;
          }
 };    
  • 1
    Do you really want to set the static variable to be zero each time an instance of "MyObject" is created? – Pixelchemist Mar 19 '15 at 13:56
  • I agree with @Pixelchemist setting the variable to 0 in the class's c'tor seems like the wrong way to go. I think you mean to set it outside the class (in @volerag answer: `int MyObject::count = 0;`) – ArnonZ Mar 19 '15 at 13:58
  • The point of static variables is that they exist independently of any instance of the object. – Neil Kirk Mar 19 '15 at 14:11

2 Answers2

4

You have to explicitly define count, as there is no definition of count. You have just declared the static variable, you have not defined it.

class MyObject
{ private:
        static int count;
        MyObject()
        {
           count=0;
        }
 }; 
int MyObject::count = 0; //Explicit definition of static variables.
shauryachats
  • 9,975
  • 4
  • 35
  • 48
0
//This is just declaration of class
class Foo
{
};

//This is definition of class
Foo obj;

When you compile your code with just line static int count;, compiler will not find definition for static variable. So it will give you an error of 'undefined reference to `MyObject::count'.

Solution:

class MyObject
{ 
private:
      static int count;
public:
      MyObject()
      {
          count=0;
      }
 };

int MyObject::count=0;

int main()
{
    MyObject obj;
    return 0;
}
shauryachats
  • 9,975
  • 4
  • 35
  • 48
CreativeMind
  • 897
  • 6
  • 19