-1

I'm currently going through the "Qt for Beginners" on https://wiki.qt.io and have come across this header and source. In the header, there is an empty class called "QPushButton".

windows.h

#ifndef WINDOW_H
#define WINDOW_H

#include <QWidget>

class QPushButton; // Empty Class
class Window : public QWidget
{
...
private:
QPushButton *m_button;
...
};

window.cpp

#include "window.h"
#include <QPushButton>

Window::Window(QWidget *parent) : QWidget(parent)
{
...
m_button = newQPushButton("Hello World", this);
...
}

My question is, would it be better to put a #include inside the header file rather than create an empty class, and remove #include in the source file altogether? It compiles and runs the same.

Like this:

windows.h

#ifndef WINDOW_H
#define WINDOW_H

#include <QWidget>
#include <QPushButton> // Added new include directive

// Removed QPushButton Class
class Window : public QWidget
{
...
private:
QPushButton *m_button;
...
};

window.cpp

#include "window.h"
// Removed include directive for QPushButton

Window::Window(QWidget *parent) : QWidget(parent)
{
...
m_button = newQPushButton("Hello World", this);
...
}

If not, please explain. Thanks!

chautr
  • 7
  • 3

1 Answers1

2

It's not an empty class, it's just a forward declaration to tell the compiler there will be a definition appearing later on. It's usually to get around this situation:

class Parent
{
  Child* pChild; ///< error, child undefined!
};
class Child
{
  Parent* pParent; ///< all good, Parent has been defined.
};

When this happens, you can add a forward declaration for Child like so:

// forward declare class to avoid compiler error
class Child;

class Parent
{
  Child* pChild; ///< Now we are all good
};
class Child
{
  Parent* pParent; 
};
robthebloke
  • 9,331
  • 9
  • 12