PDA

View Full Version : Variable question



MarkoSan
15th March 2007, 08:01
Hi to all, long time no see!!!

I have a question now:

In my project I will need variable that will hold the database connection. The variable will be initialized at application startup and all for objects in the application it is a must to see it. How and where do I put such a variable, that must be seen by all objects in an application? I want to follow c++ rules and I heard global variables are BAD idea. I also want to know why are global variables such a bad idea?

vermarajeev
15th March 2007, 08:21
Hi to all, long time no see!!!

I have a question now:

In my project I will need variable that will hold the database connection. The variable will be initialized at application startup and all for objects in the application it is a must to see it. How and where do I put such a variable, that must be seen by all objects in an application? I want to follow c++ rules and I heard global variables are BAD idea. I also want to know why are global variables such a bad idea?

You can make the variable static. Static variable applies to the class.

Global variables are dangerous coz a global variable can potentially be modified from anywhere, and any part of the program may depend on it.

MarkoSan
15th March 2007, 08:30
Yes, but I need a variable that will be seen to all objects in an application, not just one object/class.

vermarajeev
15th March 2007, 08:54
Yes, but I need a variable that will be seen to all objects in an application, not just one object/class.

Try something like this


//GlobalClass.h

// forward declaration
class GlobalClass;
// global GlobalClass object
// there must only be one of these per application (like qApp)
// defined and initialized in GlobalClass.cpp
extern GlobalClass *chemGlobals;

class GlobalClass : public QObject
{
Q_OBJECT

public:
GlobalClass(int var = default){}
virtual ~GlobalClass(){}

private:
int m_val;
};

////GlobalClass.cpp
#include "GlobalClass.h"

// global ChemGlobals object
// there must only be one of these per application (like QApp)
ChemGlobals * chemGlobals = 0;

sunil.thaha
15th March 2007, 15:59
It would be better if you try not using global variable. The singleton pattern would be a better candidate here. The advantages are many ...