If you have ever looked at the Qt source code, you have probably noticed that they use private classes and d-pointers. At first time when I saw this, I thought that what the heck is that thing and what are all these Q_D() and Q_Q() macros? I am probably not the only one that was bit confused about what they really do and what do you gain by using them. This is one reason why I decided to write a small article of using d-pointers. Most of the stuff in this article is based on KDE TechBase documentation.

Before continuing let’s take a look at how the code looks when using d-pointers inside methods.

...
void MyClass::setFoo( int i )
{
    Q_D(MyClass);
    d->m_foo = i;
}

int MyClass::foo() const
{
   Q_D(const MyClass);
   return d->m_foo;
}
...

In the example above, there are two methods. One for setting the value and another one for getting the value from the internal member of the class. Usually you would introduce an instance variable (int m_foo;) in a private section of the class MyClass and then you modify or return the value of it. In the example above, you set the integer ‘i’ to the  instance member m_foo of the private class. Next you might ask what do you gain of using this approach instead of using a “traditional way”, as it’s done in the most of the C++ code.

continue reading…