tags:

views:

67

answers:

2

Is it reasonable to use private static variables to establish invariants in your class?

Ex:

class MovingObject
{
public:
    //...Stuff
private:
    // Invariants
    static const double VELOCITY; // Moving objects always move at this velocity
    // etc. for any other invariants
    //...
}
---------------------------------------------------------------------------------
#include "MovingObject.h"
// Invariants
const double MovingObject::VELOCITY = 256.5;
//etc.
A: 

Yes, though those are generally called 'constants'. See the article anon linked for a discussion of 'invariant' as it's generally used in object-oriented design.

David Seiler
+1  A: 

Sure. This is a common idiom across several OO languages including Java.

Asaph
Thanks. I ask because I was reading about possible issues that may occur if you try multi-threading with statics.
Anonymous
The MT issues with statics in C++ mostly show up when you're both reading and writing to them. You've already declared `VELOCITY`const which implies that you're only reading from it. Read access from multiple threads is fine as long as nothing potentially changes them from underneath you.
Timo Geusch