Monday, January 17, 2005

Symbol referencing errors for static variable in C++

Are you stuck with static symbol referencing errors in ur code??
What could be wrong in the following definition of a c++ class to find out how many instances of MyClass are created??
class MyClass{
 private:
   static int __instance_count;
 public:
    MyClass(){
         __instance_count++;
    }
    int getInstances(){
      return __instance_count;
    }
};
main(){
....
}
When complied with g++ says that __instance_count is not defined...this can be resolved by defining __instance_count outside the class definition,as follows.
int MyClass::__instance_count;
Why do we need this seperate definiton of static variables?

No comments: