Is it a good style to always use static const rather than #define in C++ O.O. programming?
Is it a good style to always use static const rather than #define in C++ O.O. programming?
I suppose it depends on what you're doing it for.
If you just need a simple number remembered and used often, then a static const sounds better than #define.
What's the advantage to use "static const" other than const, especially as a class member variable?
Static simply means there will only be a single instance of it. Well, simplified anyway. If you have a lot of classes, you can make it static, since you won't be needing more than one instance (the number won't change anyway!).
But if it's not used in classes, and it's global, then there's no point. I'd rather make const variables that replaces defines global since they're just values to be read (and probably not read at all, but substituted in the code by the compiler in release mode).
I don't know if there's a disadvantage with const variables to replace define. Since it's const, you're telling the compiler the value won't ever change and it can optimize away the variable and put the real value it contains where it's used instead.
If you are defining a constant to be shared among all the instances of the class, use static const. If the constant is specific to each instance, just use const (but note that all constructors of the class must initialise this const member variable in the initialisation list).
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)