While going through Qt code I had this basic question on the pimpl implementation.
As an example taking QWidget implementation.
QWidget ---inherits---> QObject
| |
contains contains
| |
\ / \ /
QWidgetPrivate ---inherits---> QObjectPrivate
Now QWidget has two instances of QObjectPrivate (through inheritance and through containment).
Why was the implementation done in this way? Isn’t it an overhead to have two instances of the same object?
There aren’t two instances of
QObjectPrivatewhen instantiating aQWidget. If you look closely at the header file forQObject, you’ll notice a protected constructor:Which sets the instance of QObjectPrivate to that passed in via the protected constructor:
This is the constructor called by all of the different
QWidgetconstructors. The QWidget constructor passes in an instace ofQWidgetPrivatewhich, as you noted, is a subclass ofQObjectPrivate. Thus, only one instance of QObjectPrivate exists in QWidget.Here’s the default
QWidgetconstructor that illustrates this: