Dewsworld
Dewsworld

Reputation: 14033

Qt forward declaration generates error

When writting class TemplateHandler, say I use TemplateHandler.h (for my the header) and TemplateHandler.cpp (for the declarations). Like

// Templatehandler.h

#ifndef TEMPLATEHANDLER_H
#define TEMPLATEHANDLER_H

#include <QObject>   // Forward declaration of QObject generates error

class QListView;     // Forward declarations
class QTextEdit;
class QModelIndex;
class QStringListModel;

class TemplateHandler : public QObject
{
  Q_OBJECT
  public:
    TemplateHandler(QListView *view, QTextEdit *textEdit, QObject *parent);
    virtual ~TemplateHandler();

  private:
    QTextEdit *mTextEdit;
    QStringListModel *mModel;
};

#endif

And the source

#include "templatehandler.h"
#include <QListView>             // Inclusion of lib
#include <QTextEdit>
#include <QObject>
#include <QStringListModel>

TemplateHandler::TemplateHandler(QListView *view, QTextEdit *textEdit, QObject *parent) : QObject(parent), mTextEdit(textEdit)
{
    mModel = new QStringListModel(this);
    QStringList templates;
    templates << "<html>" << "</html>" << "<body>" << "</body>";
    mModel->setStringList(templates);
    view->setModel(mModel);
    connect(view, SIGNAL(clicked(const QModelIndex&)), SLOT(insertText(const QModelIndex&)));
}

TemplateHandler::~TemplateHandler() {
    // TODO Auto-generated destructor stub
}

But in this case forward declaration of QObject generates error, however the rest are okey. I need some help on that.

Upvotes: 2

Views: 10729

Answers (2)

Rohan Prabhu
Rohan Prabhu

Reputation: 7302

You are inheriting from QObject, and forward declarations to a base class do not work. This is because when a class is inherited from, the compiler needs to know the size of the class, which as Koying mentioned, requires including the .h file.

In all other cases, you use pointers to the forward declared classes. Pointers being nothing but memory addresses, don't need to know the entire size of the class, since the size of a pointer to it will just be the size required to store a memory address (depending on the architecture, platform etc.). If you tried making a member like QListView listView instead of QListView* listView, then you would still face similar problems.

Upvotes: 4

Chris Browet
Chris Browet

Reputation: 4266

This is a pure c++ "issue".

Forward declarations only work when the compiler do not need the size of the class at the time the header is included. E.g. for pointers, even to class, it knows the size.

On the other hand, for object created on the stack or for parent classes, it needs to know the exact size of the struct (e.g. sizeof(QObject)), which it can only get by including the .h.

Upvotes: 10

Related Questions