C++ Instance and Static Members


  • instance variable: a member variable in a class. Each object has its own copy.
  • Default variable modifier for classes
  • static variable: one variable shared among all objects of a class
  • if you change a static variable in one object, it gets changed in all objects
  • static member function: can be used to access static member variable; can be called before any objects are defined
  • cannot access any instance variables

static member variable example:





i. In the Tree class, every time a new instance is created, it increments the objectCount variable
ii. objectCount is the same across all Tree objects

c. static member function

i. Declared with static before return type: static int getObjectCount() const { return objectCount; }
ii. Static member functions can only access static member data
iii. Can be called independent of objects: int num = Tree::getObjectCount(); // no object needed to invoke the method, as getObjectCount is static

d. Why use static variables?

i. Unique ID’s for every instance of a class (based off of number of objects)

ii. Internal lookup tables – making the var static allows memory savings by keeping a single version for all instances of the class

e. The this pointer

i. this: predefined pointer available to a class’s member functions
ii. Always points to the instance (object) of the class whose function is being called [to override local scope]
iii. Is passed as a hidden argument to all non-static member functions
iv. Can be used to access members that may be hidden by parameters with same name
v. Example: class SomeClass { private: int num; public: void setNum(int num) { this->num = num; } … };

Leave a Reply