rcplusplus rcplusplus - 4 months ago 26
C++ Question

How is this Qt boilerplate constructor not recursive?

So when you create a standard Qt5 widget application, this is the boilerplate code for the

QMainWindow
subclass:

mainwindow.h


#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private:
Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H


mainwindow.cpp


#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}

MainWindow::~MainWindow()
{
delete ui;
}


So the class has an instance of itself, that seems fine. But then that instance itself would have an instance of itself, which in turn would have an instance of itself...

How does this not lead to an infinite recursion of classes containing themselves?

Answer

These are not the same classes. MainWindow is declared in the global namespace, while the ui member is of type Ui::MainWindow, which is declared in the Ui namespace. You can see the declaration of this class by looking at ui_mainwindow.h.

Since these are two different types, no recursion will happen, since MainWindow::~MainWindow() will not be called from within itself.