kimfalk posed a question about static functions in a class in to which my reponse was duly correct by

You're mixing up your statics. :) static is overloaded for too many different uses. In a class declaration, static means that the name belongs to the class and not to individual objects. In a function definition, static means that the variable being declared has static storage duration. In the global scope, static is a deprecated feature that forces internal linkage.

Of 262 pages of text devoted to the subject of classes in C++ Primer Plus, I somehow missed the two paragraphs that were devoted to this topic.

I'm assuming the lack of attention is due to unlikelyhood of use, but would appreciate a practical example that is not taken from any theoretical text. To me it seems somewhat analogous to declaring all variables public, defeating the purpose of encapsulation to begin with and OOP as a whole.

>would appreciate a practical example that is not taken from any theoretical text
It's often useful to keep a reference count of how many objects are in existence at any given time. However, it's not always practical to have an object to call a member function on. Therefore, you need a static class variable to keep the reference count and a static class function to get the reference count without having to access an object:

#include <iostream>

using namespace std;

class A {
  A() { ++ref_count; }
  static int references() { return ref_count; }
  static int ref_count;

int A::ref_count = 0;

void stuff()
  cout<< A::references() <<endl;

int main()
  A a, b, c;


Got it. I'm going to experiment what will happen by calling without scoping and referencing ref_count as a.ref_count etc.

I still don't see a practical way I can use this, but your example makes it crystal so if I elect to do so I shouldn't have any problems.

This article has been dead for over six months. Start a new discussion instead.