0

I am learning how to use Qt. I am in the middle of the beginner's tutorials, and I ran into a problem.

I have this class here:

#ifndef WINDOW_H
#define WINDOW_H

#include <QWidget>

class QPushButton;
class Window : public QWidget
{
    public:
        explicit Window(QWidget *parent = 0);

    private:
        QPushButton *m_button;
};

#endif // WINDOW_H

I know the purpose of any row but this one:

class QPushButton;

In my all years I learned cpp, I never encountered this such a thing. I know that when I want to declare a class, I have to do this with this basic template:

class ClassName:
{
    public:
        //Optional public.
    private:
        //Optional private.
}

But one row declaration?

I want to ask more then that:

  • Why do the Qt guys work like this?
  • Why don't they #include" the QPushButton in the header?

They included this button class within the implementation. Why?:

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

Window::Window(QWidget *parent) :
 QWidget(parent)
{
    // Set size of the window
    setFixedSize(100, 50);

    // Create and position the button
    m_button = new QPushButton("Hello World", this);
    m_button->setGeometry(10, 10, 80, 30);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
link Go
  • 13
  • 4
  • 2
    https://stackoverflow.com/q/4757565/1896169 – Justin Nov 01 '17 at 21:10
  • 1
    forward declaration, to avoid circular loop in header files. – m. c. Nov 01 '17 at 21:26
  • 1
    @m.c. ... and to reduce the amount of code the compiler has to parse when compiling files which `#include` the header containing the forward decl. – Angew is no longer proud of SO Nov 01 '17 at 21:45
  • Lookup Forward declaration. – Victor Nov 01 '17 at 21:55
  • @Victor Ok.. I knew this thing about function, but it was new to me that it can be done generaly. just to be clear - the Qt guys aclocated a new memory for the `QPushButton` new object, while they could put it in the stack as a usual variable, without loosing any system abilities? – link Go Nov 02 '17 at 09:33
  • `they could put it in the stack` Putting m_button inside Window class means to have the same memory allocation, as Window object(s), which is not necessarily on the stack. In fact, the only overhead is an extra call of a memory allocation routine (QPushButton's constructor must be called anyway), which is a common thing in C++. But the gain could be significant in medium or large project development: if class A is used in Class B, which is used in class C, then changing A won't require recompiling C. So it's a good habit, though it's not so important in this particular example. – Matt Nov 02 '17 at 16:24

0 Answers0