View Full Version : could somebody please explain const to me?

25th September 2006, 22:47
sorry for posting what i am afraid is a pure c++-problem here, but at least it is about a qt-program:
i have a loop going through a query and a QMap where i want to store the type and name of each column that is found. so i am trying to put the result of QSqlField::type() into my QMap, but this gives an error because it is const. Why is that? after all i had expected i am actually only copying the value into my QMap so no need to care about the original being const?
the code looks like this:

while (query.next()) {
QSqlRecord rec = query.record();
for (int col=0;col<rec.count();col++) {
QSqlField field = rec.field(col);
if (row == 0) {
QMap<QString,QVariant>* currCol = &columns.value(col);
currCol->insert("type",field.type()); // first error
currCol->insert("name",field.name()); // second error
qDebug() << "working on row " << row << ", column " << col;
tableData.value(row) = rec; //third error
and in the .h i have:

QMap<int,QSqlRecord> tableData;
QMap<int,QMap<QString,QVariant> > columns;

the errors i am getting are all like this:

passing `const QString' as `this' argument of `QString& QString::operator=(char)' discards qualifiers

25th September 2006, 23:29
Please post the exact error messages and tell us which lines they correspond to.

25th September 2006, 23:50
QMap<QString,QVariant>* currCol = &columns.value(col);
currCol->insert("type",field.type()); // first error
currCol->insert("name",field.name()); // second error

According to trolltech's docs value() method of QMap class returns const value:

const T value ( const Key & key ) const
so you cannot assign address of this value to pointer to non-const objects.

There is also another problem. What value() returns is temporary object. It's not advisable to take and use address of temporary object.

BTW: "Edit" button doesn't work under Opera.

26th September 2006, 06:33
yes, that was the problem - damn... i had that one before. the problem was, that at first the lines were

columns.value(col).value("type") = field.type();
columns.value(col).value("name") = field.name();
and since i splitt that a little to make it better readable i didn't look at the line above anymore, especially as i understood the errormessage to be complaining about field.type() being a const QString not about the part on the left side being const. obviously this is also the problem with the third error. Thanks

29th September 2006, 14:34
nothing specific to the problem but as an explaination of 'const', (among many other things)