Reputation: 818
I'm having trouble understanding the use of private static attributes in a class :
-> private means the attributes will only be accessible from the class itself if I'm correct
-> static indicates the attributes belong to the class itself and not the object and, if I'm still correct, which permit to access it without creating an object
So, I can't imagine any use of a private static attribute.
Thanks in advance for any help :)
Kenshin
Upvotes: 0
Views: 1255
Reputation: 40406
Here's another example that might expand your imagination:
class NotAThreadSafeExample {
public:
NotAThreadSafeExample () { ++ debugReferenceCount; }
~NotAThreadSafeExample () { -- debugReferenceCount; }
static int getDebugReferenceCount () { return debugReferenceCount; }
private:
static int debugReferenceCount;
};
Or:
class Example {
private:
static const int FIXED_COLUMN_WIDTH = 32;
};
Or maybe even something like this, where appropriate (atomicIncrement
left to your imagination, e.g. InterlockedIncrement()
on Windows or __sync_add_and_fetch()
with GCC; integral type record_id_t
chosen accordingly):
class Record {
public:
Record () : id(atomicIncrement(&nextId)) { }
record_id_t getId () const { return id; }
private:
static volatile record_id_t nextId;
record_id_t id;
};
Or any other use you can imagine for a static
variable that is not accessible outside of a class or its friend
s.
Upvotes: 1
Reputation: 254741
You said it yourself: if you want a variable associated with the class but not part of any object (static
), that can only be accessed within the class itself (private
).
As a concrete example, here's a class that counts instances of itself:
class countable {
private:
static unsigned count;
public:
countable() {++count;}
countable(const countable&) {++count;}
~countable() {--count;}
static unsigned instance_count() {return count;}
};
Upvotes: 6
Reputation: 30146
Here is an example that might expand your imagination:
class Singleton
{
public:
static Singleton* getInstance();
~Singleton();
private:
Singleton();
static Singleton* instance;
};
Upvotes: 3
Reputation: 7778
A friend
class or function could access this static member.
Upvotes: 0