PDA

View Full Version : QSharedDataPointer and Data with virtual functions



niko
2nd February 2010, 09:23
Hi,

I want to use QSharedDataPointer for multiple inherited data classes with virtual functions.
Attached code that implements that - and is actually working.
My question: Is this a good idea, are there problems I don't see or is there a better way to implement this?

thanks,
Niko



//Employee/EmpoyeeData as in Qt docs for QSharedDataPointer
//addition: virtual int salary()
class EmployeeData : public QSharedData
{
public:
EmployeeData() : id(-1) { name.clear(); }
virtual ~EmployeeData() { }
virtual EmployeeData *clone() {
return new EmployeeData(*this);
}

virtual int salary() const { return 10000; }

int id;
QString name;
};
template<>
EmployeeData *QSharedDataPointer<EmployeeData>::clone()
{
return d->clone();
}

class Employee
{
public:
Employee() { d = new EmployeeData; }
Employee(int id, QString name) {
d = new EmployeeData;
setId(id);
setName(name);
}
Employee(const Employee &other)
: d (other.d)
{}
virtual ~Employee() { }
void setId(int id) { d->id = id; }
void setName(QString name) { d->name = name; }

int id() const { return d->id; }
QString name() const { return d->name; }
int salary() const { return d->salary(); }

protected:
Employee(EmployeeData *d_) { d = d_; }
QSharedDataPointer<EmployeeData> d;
};
QDebug operator<<(QDebug dbg, const Employee &e) {
dbg.space() << e.name() << e.salary();
return dbg;
}

class BossData : public EmployeeData
{
public:
virtual int salary() const { return 50000; }

virtual EmployeeData *clone() {
return new BossData(*this);
}
};

class Boss : public Employee
{
public:
Boss() : Employee(new BossData) { }
Boss(int id, QString name) : Employee(new BossData) {
setId(id);
setName(name);
}
};