Consider this code:
#include<iostream> using namespace std; class Wilma { public: static int i; Wilma() { cout<<"\nWilma ctor\n"; cout<<"\ni::"<<i<<"\n"; } }; class Fred { public: Fred() { cout<<"\nFred ctor\n"; } static Wilma wilma_; }; int Wilma::i=44;//------------- LINE A int main() { int a=0; Wilma::i=a;//---------- LINE C Wilma w; Fred::wilma_=w;//---------- LINE B }
here, line A explicitly defines a static int a of the Wilma class (commented out to cause a linker error) and without which linker gives a link to undefined. (because Wilma :: I actually used, if I do not use it, there are no linker errors.)
The same should be true for the static Wilma wilma_ class of Fred, i.e. it must be explicitly defined as ... because it is also used in the code on line B. But it is not, no linker errors for Fred :: wilma_ unless it was explicitly defined. What for? Tested on gcc 4.5.2
EDIT: For some reason, I got another doubt about this ...
LINE C and LINE B both try to use static objects of class int Wilma::i and Wilma Fred::wilma_ respectively. But only the definition for int Wilma::i ?
Why isnt Wilma Fred::wilma_; required?
I understand the answer that line B is not working. but the same can be said about the line C ??
source share