C++ best practice of defining database and time variables

As SQLITE database of application needs to be accessed in both .main and .cpp by many functions, what is the best practice for accessing it? Should it be defined in main and inside every function separately with difference names OR it's best to define it globally and then, open and close within different functions?
If it should be defined globally, give an example on where and...?!

Same question for time variables using localtime_s?
Last edited on
it sounds like you need an object that handles the database connection and does a send sql get result back type interface that everything else can use. you then have choices ... the object can have a static function to do the sql part, or you can pass something around as a parameter, or whatever else.

not sure where you are in your studies of c++, but global variables are an easy way to make a small program work that cause tons of problems once your program gets just a little bit bigger than what a classroom needs you to do and are never a best practice (there are a few exceptions where they are used, but best practice is about generalizations and in general, they never are a good idea.. the exceptions can be discussed much later when you have specific needs).

that said, objects make a sort of (in the loosest sense of the term) "scoped to the object" "global" variable set that the object's own methods treat as global variables (sort of). They are similar in that you can access them without passing them to every method, at least, and they keep the values around outside of the method bodies, etc. You get many of the benefits, and only a small subset of the drawbacks this way. (eg different functions can set class variables and change the state unexpectedly just like a global, you just have to not mess up on that stuff, but the damage is contained to one object, not the whole program).
Last edited on
Topic archived. No new replies allowed.