Click here to Skip to main content
12,898,392 members (55,602 online)
Rate this:
Please Sign up or sign in to vote.
See more: C++
Hi I am having this error and would be nice if someone could help.

In my class header file I have declared following:

class CStudentClass
    static int m_currentNumberOfStudents;

However when I try to use the above private variable in .cpp file I get an error saying:

1>StudentClass.obj : error LNK2001: unresolved external symbol "private: static int CStudentClass::m_currentNumberOfStudents" (?m_currentNumberOfStudents@CStudentClass@@0HA)
1>c:\my documents\Projects\Student_Class\Debug\Student_Class.exe : fatal error LNK1120: 1 unresolved externals

What am I doing wrong? thanks

I tried referring to this variable in my .cpp file both using: m_currentNumberOfStudents and CStudentClass::m_currentNumberOfStudents but both seem to fail??
Posted 8-Dec-12 2:57am
Updated 8-Dec-12 2:58am
Before considering the problem, it's good to think: why using static field at all. This should be done only in special cases. Usually, using such fields can be eliminated; and it's the best to avoid them.

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Static members have to be defined inside the .cpp file, something like this:
int CStudentClass::m_currentNumberOfStudents = 0;

(This is in addition to the declaration inside the class.)
Graham Breach 8-Dec-12 10:57am
No - the line of code goes outside of any functions, and only initializes the variable once at program start-up.

If you want each instance of the class to have its own number of students, then use a non-static member variable instead and initialize it with the class constructor. Of course you can do both, but you would have to give them different names.

This stuff should be near the start of any decent C++ text book.
Graham Breach 9-Dec-12 5:54am
Then you use the static member variable and increase or decrease its value.
Graham Breach 9-Dec-12 7:40am
No, because you don't initialize the static member variable in the constructor - initialization goes outside of any functions and only runs once.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.170424.1 | Last Updated 8 Dec 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100