since it is constant you can move it out to the global scope as a constant expression, or even into a header file.
Constants are NOT variables :)
Constants cannot change and while in large programs are probably best put into a namespace (and at global scope), for smaller programs global access is fine without the namespace. Variables can change, and are not so hot at the global scope.
it also can be determined by where you need it. If the whole program needs it, that is global, but if only one area needs it, maybe it belongs in the class header, or a local cpp file scope, .... get it where it needs to go, and try to limit it so it goes no farther than that, as programs get bigger this becomes more and more of a good thing to do.
I remember opened a thread 3 years ago with almost the same argument.
"Constants are NOT variables :) "
I know, sorry, but i mean both
SCREEN_WIDTH, SCREEN_HEIGHT and scrollingYOffset
If i create an header to hold few global var and constant is consider a bad practice?
variables globally are a bad practice, yes. Constants are fine; I have somewhere one with like 50 common math constants like pi, e, rad2deg, etc...
can you make the y-offset a static class member? Then if it changes in one, it changes for all objects of that class. If its needed by other classes, you can do something else ... how far reaching is it? Can you pass it into constructors? Should to take a pointer or reference to it? Does it need to be thread safe?
Yes, if you are a compiler, and it should have been a constant expression instead, but that aside... the issues from global varying data items are caused by the ability to write to them. I am unaware of any problems caused by reading an item that cannot (or, for that matter, simply does not) change.
Create a header which defines these compile time constants. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13
// screen_geometry.h
#ifndef SCREEN_GEOMETRY_H_INCLUDED
#define SCREEN_GEOMETRY_H_INCLUDED
namespace screen
{
staticconstint WIDTH = 640; // C++11: we can use constexpr instead of const
staticconstint HEIGHT = 480; // eg, constexpr int HEIGHT = 480;
staticconstint scrollingYOffset=0;
}
#endif // SCREEN_GEOMETRY_H_INCLUDED
Include this header in the header for the two classes. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Ltexture.h
#ifndef LTEXTURE_H_INCLUDED
#define LTEXTURE_H_INCLUDED
#include "screen_geometry.h"
class LTexture
{
// use screen::WIDTH instead of SCREEN_WIDTH
// use screen::HEIGHT instead of SCREEN_HEIGHT
// use screen::scrollingYOffset instead of scrollingYOffset
};
#define LTEXTURE_H_INCLUDED