// static.cc test various cases note //! is about 'static' FOUR USES !! // 1 a static member function // 2 a static member variable (shared by all objects of this class // 3 local to this file // 4 static (not on stack) variable in function - holds value // between calls to the function #include using namespace std; static int funct(int stuff); //! local to this file, not seen by linker 3 class Base { public: Base(void) { B2=2; B3=3;} static void BF1(void); //! definition can not go here 1 void BF2(void) { cout << B1 << " " << B2 << " BF2 in Base \n"; B2=5; } private: static int B1; //! no =1; here (shared by all objects of this class) 2 int B2; int B3; }; int Base::B1 = 1; //! has to be at file scope. Not in 'main' or in class 2 //! only one per total program, not in .h file void Base::BF1(void) //! can not use word static in front of this { cout << B1 << " BF1 static in Base \n"; //! can not use B2 or B3 in here B1=4; } static int j=3; //! means local to this file, not visible to linker 3 static Base c; int main(void) { static int i; //! means not on stack, value saved from call to call 4 Base a, b; a.BF2(); a.BF1(); //! object can be used, any object, same result a.BF2(); b.BF2(); Base::BF1(); //! no object needed, but do need Base:: syntax b.BF2(); return funct(-2); //! call to function, local to this file } static int funct(int stuff) //! local to this file, not seen by linker 3 { static int i=4; // hold value between calls to funct 4 j=i; i++; return stuff+3; } // results, note B1 is changed in object 'a' and B1 gets changed also in 'b' // while B2 is changed in object 'a' and 'b' unaffected // 1 2 BF2 in Base B1==1, B2==2, B2=5 in 'a' // 1 BF1 static in Base B1==1, B1=4 global // 4 5 BF2 in Base B1==4, B2==5, B2=5 in 'a' // 4 2 BF2 in Base B1==4, B2==2, B2=5 in 'b' // 4 BF1 static in Base B1==4, B1=4 global // 4 5 BF2 in Base B1==4, B2==5, B2=5 in 'b'