Short Problem:
How should I check if integers are undefined, just as I can check QStrings for having NULL values?
Backstory:
This is my coding style when I am trying to avoid overloading my functions.
myclass.h
public:
QString string(); // Return private member variables
int integer();
void setString(QString s); // Set private member variables
void setInteger(int i);
signals:
void stringChanged(); // Signal that member variable has been changed
void integerChanged();
protected:
void myFunction(); // Internal functions
void resetMemberVariables();
private:
QString m_String; // Private member variables
int m_Integer;
myclass.cpp
QString MyClass::string()
{
return m_Integer;
}
int MyClass::integer()
{
return m_Integer;
}
void MyClass::setString(QString s)
{
m_String = s;
emit stringChanged();
}
void MyClass::setInteger(int i)
{
m_Integer = i;
emit integerChanged();
}
void MyClass::myFunction()
{
if (!m_String.isNull()) {}
if (!m_Int.isNull()) { /* This is obviously impossible */ }
resetMemberVariables();
}
void MyClass::resetMemberVariables()
{
if (!m_String.isNull()) {
m_String = QString::null;
emit stringChanged();
}
if (!m_Integer.isNull()) { // Impossible
m_Integer = NULL; // Pretty sure this is wrong
emit integerChanged();
}
}
TLDR:
Instead of using parameters in functions, I let the user set member variables, and have code execute depending whether or not that member variable has been defined. At the end, I reset all member variables to a NULL value.
From what I understand, int
can not have a NULL value because every memory space can be interpreted as an integer. (Please correct me if this is wrong.)
So how should I check whether my int
variables have been set?
- Should I reserve a dummy number?
- Should I pair it with a bool?
- Maybe I should make a
QPair<int,bool>
, the bool toggling its defined or undefined state?
Best Answer
The best solution would be to avoid the possibility to ever have an uninitialized integer, by passing the value with the constructor. This way the user of your class is forced to pass a value if he wants to create an instance of your class. If you assume the user will not pass an undefined int, the requirement to check this dissapears.
Of course it can be so that the value of the int cannot be provided untill after instanciation. If this is the case you can fall back to the default value approach, but you should definitely try your best to avoid that if possible.