Microsoft Interview Question
Software Engineer in Tests@Tarun - I think tarun is right. Static variables are only glorified globals to which the access is protected by the compiler...
If you notice, static variables require no initialization to 0... meaning they don't contain garbage - they automatically are initialized to 0. This is a characteristic trait of globals in C/C++... Just a thought...
Only 1 bug:
1. static is a declaration not a definition, because you can not define static data inside a class so you have to define it outside the class, after class definition either in header file but more appropriately in corresponding .cpp
@Rashmi: According to above fact, you don't get compiler error since compiler's job is done by the declaration only, when linker tries to find i's definition it couldn't find because it is not defined outside and after the class A, so linker complained undefined reference just when linker was trying to resolve print() function's address. Also, static member data and static member functions are property of the class and bound to class only not to any object so you can call static member functions through objects also and static member data also can be accessed!
Only 1 bug:
1. static is a declaration not a definition, because you can not define static data inside a class so you have to define it outside the class, after class definition either in header file but more appropriately in corresponding .cpp
@Rashmi: According to above fact, you don't get compiler error since compiler's job is done by the declaration only, when linker tries to find i's definition it couldn't find because it is not defined outside and after the class A, so linker complained undefined reference just when linker was trying to resolve print() function's address. Also, static member data and static member functions are property of the class and bound to class only not to any object so you can call static member functions through objects also and static member data also can be accessed!
This is a linker error, because A::i was declared but not defined.
- Anonymous December 28, 2010