1

Why this code is giving me an error that undefined reference to student::count. I am using static count and I know that static members are by default is 0 but dont know why giving me an error. Please explain me.

#include <iostream>
using namespace std;

class Student{

static int count;
string name;


public:

    Student(){
        count++;
        cout<<"I am  student"<<count<<endl;

    }
    int getCount() const
    {

        return count;
    }

    void setCount(int x){
        count=x;

    }


};

int main(){

Student stud[20];


return 0;
}
4
  • 2
    You forgot to do int Student::count;
    – David G
    Commented Mar 1, 2014 at 22:39
  • "Giving me an error" There are lots of kinds of errors. The more specific you are, the more quickly otherx can help you. Commented Mar 1, 2014 at 22:41
  • please also tell me about static constant? I just want to understand that Commented Mar 1, 2014 at 22:42
  • thanks i got it now i forgot to use int Student::count Commented Mar 1, 2014 at 22:43

2 Answers 2

1

You have no definition of Student::count, violating the one definition rule. Put a definition in one, and only one, translation unit.

Note that if static int count; was a definition, static members would be almost impossible to use. You'd wind up with a definition each time you included the header file, making the one definition rule almost impossible to comply with.

0

Writing static int count; in your header means: Compiler, somewhere you will find a variable scoped to this class, it will be a int and will be nammed count.

Now, you need to actually instantiate (define) your variable somewhere. Maybe in your case, adding int Student::count; to your main file would be fine.

Not the answer you're looking for? Browse other questions tagged or ask your own question.