Dave M. Dave M. - 1 month ago 10
C++ Question

In Qt MainWindow, why does an instance have a pointer to an instance?

The

MainWindow
code generated by QtCreator says:

namespace Ui {
class MainWindow; // forward-declare Ui::MainWindow (?)
}

class MainWindow : public QMainWindow // Declare MainWindow class (Ui::MainWindow?)
{
Q_OBJECT

public:
explicit MainWindow( QWidget *parent = 0 );
/**/ ~MainWindow( void );
// ...
private:
Ui::MainWindow *ui;
// ...
};


main()
does:

MainWindow w;
w.show( );


MainWindow::MainWindow( QWidget *parent )
does:

ui( new Ui::MainWindow ) // Initialization


I don't understand why a
MainWindow
instance has a pointer to another/a different/a new
MainWindow
in its
ui
instance variable. I instrumented the
MainWindow::MainWindow
constructor, and I can see it's only being called once. So presumably that's the automatic variable on the stack in
main()
. But what about the
ui( new Ui::MainWindow )
that happens in the constructor? That's creating a
MainWindow
on the heap, isn't it? How is it being initialized?

Maybe the subsequent
ui->setupUi( this )
in the constructor is doing some magic? Otherwise, it seems like this would recurse to stack crash, as each
new MainWindow
creates a new
MainWindow
to populate its
ui
instance variable.

Answer

There are two different classes in play here:

::MainWindow
::ui::MainWindow

I wouldn't go so far as to say they are not related - but they are not the same class.

Comments