PDA

View Full Version : Accessing to a static variable from the same class



xgoan
28th February 2007, 16:58
Hi,

I'm implementing a class to do operations with a SQLite database and I have this header file


...
class ObjectDatabase{
public:
static bool openDatabase(QString);
static bool createTables();
static void closeDatabase();
static bool vacuumDatabase();
static QString errorString();
protected:
static void setErrorString(QString);
private:
static QString m_errorString;
};
...

But when I try to access from this functions to the var m_errorString the compiler say that the var isn't defined.

What can be the problem?

Thank's

Michiel
28th February 2007, 17:40
I don't see an error in the code you posted. That means that the error is somewhere else. A typo, perhaps? Maybe your function definition doesn't have "ObjectDatabase::" in front of the name?

If that doesn't help, could you copy/paste the code where you try to access the variable?

jpn
28th February 2007, 19:24
Define the static variable in the .cpp file:


QString ObjectDatabase::m_errorString;

Michiel
28th February 2007, 19:38
Oh, you're right. I admit I've never used static variables in C++ in that way. How silly.

xgoan
1st March 2007, 09:28
So the code that works is this:

objectdatabase.h

...
class ObjectDatabase{
public:
static bool openDatabase(QString);
static bool createTables();
static void closeDatabase();
static bool vacuumDatabase();
static QString errorString();
protected:
static void setErrorString(QString);
private:
static QString m_errorString;
};
...

objectdatabase.cpp

...
QString ObjectDatabase::m_errorString;
...
void ObjectDatabase::setErrorString(QString string){
m_errorString=string;
}
...

Thanks to all

Kumosan
5th March 2007, 11:02
Now we could start a discussion, whether the whole static stuff is good design, or if it is better be done as a singleton. Classes with nothing else but static methods and static members always make me a bit nervous. ;)

wysota
5th March 2007, 11:50
You can always convert such class to a namespace with functions and global objects if you don't like a static class :]