I’ve created simple snippet to show strange behavior I noticed. That’s it:
#include <QCoreApplication>
#include <QLineEdit>
class MyObject : public QWidget
{
public:
explicit MyObject(QWidget *parent = 0) : QWidget(parent) {
editor = new QLineEdit(this);
}
void setValue(const QString &s) const {
editor->setText(s);
editor->setReadOnly(true);
editor->setMaxLength(s.length());
}
private:
QLineEdit *editor;
};
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
return app.exec();
}
MyObject::setValue function has const specifier, but this code is compiled well. Note that setText, setReadOnly and setMaxLength functions aren’t const:
void setText(const QString &);
void setReadOnly(bool);
void setMaxLength(int);
I just want to know what causes such behavior?
I use Qt 4.7.4 with MingGW 4.6.2.
(This is not Qt related. This is a general C++ question.)
The compiler is correct, because you are not modifying
editor. What you are modifying is*editor; you are only modifying the object it points to. Theconstspecifier will only disallow changing members directly contained in the object. The objecteditorpoints to is not a member and thus can be modified: