Is this a way of achieve "internal class"?



  • Not sure if I should post it here or in Qt Embedded, but I am reading the code of class QWSDisplay in gui/embedded/qwsdisplay_qws.h. It define a member "d" this way:
    @
    ...
    class Data;
    friend class Data;
    Data d;
    ...
    @
    Then in qapplication_qws.cpp it starts to define methods of "Data":
    @
    ...
    QWSDisplay::Data::Data(QObject
    parent, bool singleProcess)
    {
    #ifdef QT_NO_QWS_MULTIPROCESS
    Q_UNUSED(parent);
    Q_UNUSED(singleProcess);
    #else
    if (singleProcess)
    csocket = 0;
    else {
    csocket = new QWSSocket(parent);
    QObject::connect(csocket, SIGNAL(disconnected()),
    qApp, SLOT(quit()));
    }
    clientLock = 0;
    #endif
    init();
    }

    ...@

    I can't find the declaration of class Data anywhere in the source. Did I just miss it or it's not necessary? If declaration in not necessary does it mean that it has no member?

    I have never seen this technique before so can somebody shed some light on it? What's the essential purpose of doing this? Is this kind of a way to create "internal class" that's only known to QWSDisplay?



  • It is not needed. It is just being forward-declared, and after that just implemented. It is basically declared and implemented at the same time in the CPP file, and there is nothing wrong with that. You do not do that normally, as you would have a very hard time using the class from anywhere else, but in this case, that is the whole point: the class is supposed to be private.

    The idiom is known as the pimpl or d-pointer idiom, and is used to hide the privates of a class. In Qt, it is mainly used to protect binary compatability and still make it possible to change/extend the private parts of the class.



  • You can find the declaration of QWSDisplay::Data in qwsdisplay_qws_p.h (the corresponding private header file).

    Yes, it's a way of hiding the private members of a class into a separate private class. It's called d-pointer pattern in Qt lingo.

    Benefits are:

    • Binary compatibility: You can change private variables in the class without changing the memory footprint of the class
    • Clean public header files: Private data members are not exposed in public headers
    • Shared data: The d-pointer makes implicit sharing and explicit sharing easier

    See also:
    http://zchydem.enume.net/2010/01/19/qt-howto-private-classes-and-d-pointers/
    http://developer.qt.nokia.com/wiki/Dpointer



  • Thanks for the reply. Especially thanks roopeshchander for the links, they really help to understand the concept of d-pointer idiom. Time to dig into pimpl...



  • My pleasure. Thanks redirected to zchyderm and girish for authoring the said articles. :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.