>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();
}
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Offline 11,807 posts
since Sep 2004