Static Member Definition

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 ??

+4
source share
2 answers

Wilma has no non-static fields. Fred::wilma_=w; doing nothing.

change

If there are no non-static members, there is no copy. Basically, the assignment was no-op and could just be optimized by the compiler, and the linker never saw it. Adding a non-static member made the copy an actual operation that referred to a static variable, so the compiler could not optimize it, and the linker saw it.

+3
source

You declared static int i; in Wilma , but did not identify him. Thus, adding back to line A, this will cause Wilma :: I to be determined , which the compiler complains about. Therefore, you should define it somewhere outside the class, and not inside the main one.

Finally, the Fred and Wilma classes are essentially empty (except for ctor and the static member of the class). There is no copy between them.

Edit: Based on the comments on @littleadv, you should have an identical class if you are going to execute a copy. If you put int j in the Wilma class, but nothing in the Fred class, then this will not work, because where should it put j in the Fred class?

+1
source

All Articles