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

Qt Code:
  1. //Employee/EmpoyeeData as in Qt docs for QSharedDataPointer
  2. //addition: virtual int salary()
  3. class EmployeeData : public QSharedData
  4. {
  5. public:
  6. EmployeeData() : id(-1) { name.clear(); }
  7. virtual ~EmployeeData() { }
  8. virtual EmployeeData *clone() {
  9. return new EmployeeData(*this);
  10. }
  11.  
  12. virtual int salary() const { return 10000; }
  13.  
  14. int id;
  15. QString name;
  16. };
  17. template<>
  18. EmployeeData *QSharedDataPointer<EmployeeData>::clone()
  19. {
  20. return d->clone();
  21. }
  22.  
  23. class Employee
  24. {
  25. public:
  26. Employee() { d = new EmployeeData; }
  27. Employee(int id, QString name) {
  28. d = new EmployeeData;
  29. setId(id);
  30. setName(name);
  31. }
  32. Employee(const Employee &other)
  33. : d (other.d)
  34. {}
  35. virtual ~Employee() { }
  36. void setId(int id) { d->id = id; }
  37. void setName(QString name) { d->name = name; }
  38.  
  39. int id() const { return d->id; }
  40. QString name() const { return d->name; }
  41. int salary() const { return d->salary(); }
  42.  
  43. protected:
  44. Employee(EmployeeData *d_) { d = d_; }
  45. QSharedDataPointer<EmployeeData> d;
  46. };
  47. QDebug operator<<(QDebug dbg, const Employee &e) {
  48. dbg.space() << e.name() << e.salary();
  49. return dbg;
  50. }
  51.  
  52. class BossData : public EmployeeData
  53. {
  54. public:
  55. virtual int salary() const { return 50000; }
  56.  
  57. virtual EmployeeData *clone() {
  58. return new BossData(*this);
  59. }
  60. };
  61.  
  62. class Boss : public Employee
  63. {
  64. public:
  65. Boss() : Employee(new BossData) { }
  66. Boss(int id, QString name) : Employee(new BossData) {
  67. setId(id);
  68. setName(name);
  69. }
  70. };
To copy to clipboard, switch view to plain text mode