#include <QMap>
#include <QString>
#include <QDebug>
class Type {
public:
Type(int i = 5) : _i(i) {}
int _i;
virtual int damnIt() { return 1; }
};
class DerivedType : public Type {
public:
DerivedType(int i = 5) : Type(i) {}
virtual int damnIt() { return 2; }
};
class Container {
public:
Container() {}
virtual Type & operator [](QString propertyName) {
if (!_properties.contains(propertyName)) _properties[propertyName] = Type();
return _properties[propertyName];
}
private:
QMap<QString, Type> _properties;
};
int main(int, char **) {
Container c;
c["hi"] = DerivedType();
qDebug() << c["hi"].damnIt();
QMap<QString, Type> direct;
direct["hi"] = DerivedType();
qDebug() << direct["hi"].damnIt();
}
Output:
$ ./test
1
1
Given the fact that QMap<K,T>::operator[] returns reference why polymorphic principle doesn't work here? What is the correct way to store heterogeneous objects in a container?