I'm having a general problem with const in classes. Here's a trivial example:
|
Source code
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
class MyClass {
private:
QString* data1;
QString* data2;
// Return a number depending on the value of param
QString* privateData(const int param);
public:
// Return a string reflecting the internal data
const QString readData(const int param) const;
// Append to the internal data
void appendData(const int param, QString* value);
// Add ctors/dtors, etc
};
QString* MyClass::privateData(const int param) {
if (param == 1)
return data1;
else
return data2;
}
const QString* MyClass::readData(const int param) const {
const QString* data = privateData(param);
return data;
}
void MyClass::appendData(const int param, QString* value) {
QString* data = privateData(param);
data->append(&value);
}
|
This example doesn't do much, but it illustrates my problem: the fundtion appendData uses the function privateData to find a QString, then writes to it. For this reason, privateData cannot be const. However, the compiler (mingw) throws an error in the function readData as it is const but is calling privateData, which is not const.
I think I could probably use const_cast to deal with this, but I'd rather find a better way, if there is one. I've always thought casts to be a bit of a hack!
Does anyone know how to do this?