kimfalk posed a question about static functions in a class in http://www.daniweb.com/techtalkforums/thread19241.html 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.

Recommended Answers

All 2 Replies

>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 {
public:
  A() { ++ref_count; }
public:
  static int references() { return ref_count; }
private:
  static int ref_count;
};

int A::ref_count = 0;

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

int main()
{
  A a, b, c;

  stuff();
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.