I think a better approach would be to hide the implementation completely and only expose the interface of MyObject to the world, like so:
class MyObject {
public:
virtual void method1() = 0;
virtual void method2() = 0;
};
class MyObjectImpl : public QGraphicsObject, public MyObject {
public:
MyObjectImpl
(QGraphicsItem *parent
= 0) : QGraphicsObject
(parent
) {} void method1() { ... }
void method2() { ... }
};
class MyObjectFactory {
public:
MyObject *createMyObject() { return new MyObjectImpl(...); }
};
class MyObject {
public:
virtual void method1() = 0;
virtual void method2() = 0;
};
class MyObjectImpl : public QGraphicsObject, public MyObject {
public:
MyObjectImpl(QGraphicsItem *parent = 0) : QGraphicsObject(parent) {}
void method1() { ... }
void method2() { ... }
};
class MyObjectFactory {
public:
MyObject *createMyObject() { return new MyObjectImpl(...); }
};
To copy to clipboard, switch view to plain text mode
You can declare the MyObjectImpl class in .cpp file to hide it completely from the developer and only expose MyObject interface. Of course if you don't allow outside world to create MyObject object, you don't need MyObjectFactory at all and can just instantiate implementation objects directly.
An exercise to the reader: which two design patterns does this approach make use of?
Added after 4 minutes:
There is also this possibility:
class MyObject {
public:
MyObject() { impl = new MyObjectImpl(this); }
void method1() { impl->method1(); }
void method2() { impl->method2(); }
private:
MyObjectImpl *impl;
};
class MyObjectImpl : public QGraphicsObject {
public:
MyObjectImpl(MyObject *o), QGraphicsObject(), iface(o){}
void method1() { ... }
void method2() { ... }
private:
MyObject *iface;
};
class MyObject {
public:
MyObject() { impl = new MyObjectImpl(this); }
void method1() { impl->method1(); }
void method2() { impl->method2(); }
private:
MyObjectImpl *impl;
};
class MyObjectImpl : public QGraphicsObject {
public:
MyObjectImpl(MyObject *o), QGraphicsObject(), iface(o){}
void method1() { ... }
void method2() { ... }
private:
MyObject *iface;
};
To copy to clipboard, switch view to plain text mode
Again, what design pattern is that? I can give a hint that it makes more sense to use it if you want to subclass MyObject one day.
Bookmarks