Static Members Sharing is caring…
Single Copy Some things only need/want one of: Constants NextID
Static Static : Shared Member for which very object of class shares value Student mascot: Storm student1 name: Bob mascot: student2 name: Jane mascot:
Static Changing static variable in one changes for all: Student mascot: Storm student1 name: Bob mascot: student2 name: Jane mascot:
Static Changing static variable in one changes for all: student1.setMascot("Bruin") Student mascot: Bruin student1 name: Bob mascot: student2 name: Jane mascot:
Special Static Rules Non-const & non-literal member variables not initialized in constructor or declaration: .h file: Get own initialization outside of class .cpp file:
Static Functions Static Functions May only access static variables Every object guaranteed to give the same answer Student mascot: Bruin student1 name: Bob mascot: student2 name: Jane mascot:
Static Functions Static Functions Every object guaranteed to give the same answer Allowed to call static functions directly on class: CLASSNAME::function()
Book Example : Counter Circle with static int : number of Circles .cpp:
Book Example : Counter Constructors add to counter
Constant Constants are good things to share: In .cpp
Constant Inside class, access via variable name: From outside the class, need fully qualified name:
Static Rules of Thumb OK to make static Think long and hard first… Constants Think long and hard first… Something you think should only be one of Functions you want to access through class Factory Functions Function Libraries (java style)