0

I'm having a hard time figuring out how the classes are defined in Qt.

I'll take the QT5 JSON API as an example:

QJsonValue is a class representing any JSON value. It can be converted to a QJsonObject, QJsonArray, or to the standard types like QString, int, etc.

Now, the QJsonValue header looks like this (I stripped non-relevant parts, the complete file is here):

#include <QtCore/qglobal.h>
#include <QtCore/qstring.h>

class QDebug;
class QVariant;
class QJsonArray;
class QJsonObject; // class is pre-declared

class Q_CORE_EXPORT QJsonValue
{
    QJsonValue(const QJsonObject &o);
    QJsonObject toObject() const; // how does this work without 
                                  // any info on QJsonObject class structure??
    // ...
}

What bothers me is that QJsonObject is pre-declared as an existing class, but I figure that without any information on the inners of the class, the toObject() method won't compile (although it doest, including only <QJsonValue> doesn't fail).

I'm not so sure about the const reference, since it might not need the full class description, but just the address.

Problem is, there is never an include of QJsonObject.h anywhere in the file.

Is this magic or what?

Gui13
  • 12,993
  • 17
  • 57
  • 104
  • 2
    It is included in the qjasonvalue.cpp file. – thuga Jun 06 '13 at 12:56
  • How does the compiler knows, with only the header file,how much space to save for this QJsonObject on the stack? *Without any information on it??* In C, if you reference a structure without defining the entirety of it, it fails, am I right? – Gui13 Jun 06 '13 at 13:05
  • 2
    See http://stackoverflow.com/a/553796/492336 – sashoalm Jun 06 '13 at 13:16
  • possible duplicate of [When to use forward declaration?](http://stackoverflow.com/questions/553682/when-to-use-forward-declaration) – sashoalm Jun 06 '13 at 13:16
  • I'm really confused about the bit where a method that is declared as returning this incomplete type can still be compiled without the compiler knowing about the return type... – Gui13 Jun 06 '13 at 13:44

1 Answers1

2

The include of the header is needed only if you define functions, but the function declarations (even ones that takes type parameters by value) only require forward declaration.

Zlatomir
  • 6,964
  • 3
  • 26
  • 32
  • From the comments to the question and this answer, it seems that C++ took a step further in letting the programmer use the least amount of header possible. I didn't know that it was possible to return full blown objects without completely defining the structure of this object. I guess the compiler has to make sense of that at compile time. – Gui13 Jun 06 '13 at 15:09
  • 1
    @xgbi: A declaration just means "there is an X". A definition means "here's the X". The compiler really doesn't have to do a lot for declarations. At most, it puts in a notice "hey, I used X" for the linker to fix up. – MSalters Jun 07 '13 at 00:21