Confusion about namespaces and classes in QT

Hi, I just started to learn QT5.5 and I kind of don't understand this simple thing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {      //start of Ui namespace
class MainWindow;        
}                   //end of Ui namespace

//Rest is defined outside this namespace
class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

In this header MainWindow class is forward declared in this Ui namespace but after that the actual definition is written outside this namespace. It just doesn't make sense. As I see it these are 2 separate classes with same name but different namespaces right?

If that is so and I dont even have to write definition for Ui::MainWindow it means that its already written and it doesn't make sense to forward declare it.

I checked this out with simple class X that I wrote and indeed they were 2 different classes if I created header this way. I could obviously use only that class that's defined outside namespace.

If I remove
1
2
3
namespace Ui {
class MainWindow;
}

part than im getting error on line Ui::MainWindow *ui; that says
'Ui' does not name a type


Probably not the right place to ask for help but ill take my chances :D
Last edited on
In this header MainWindow class is forward declared in this Ui namespace but after that the actual definition is written outside this namespace. It just doesn't make sense. As I see it these are 2 separate classes with same name but different namespaces right?

Correct. Two different classes.

If that is so and I dont even have to write definition for Ui::MainWindow it means that its already written and it doesn't make sense to forward declare it.

It does if we want the line Ui::MainWindow *ui; to be accepted by the compiler. Just because something has been defined in some other file somewhere else doesn't mean the code in this file magically knows about it.
Last edited on
Ohh tnx man, I think I started to understand it tnx to you!

This is the corresponding mainwindow.cpp file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "mainwindow.h"
#include "ui_mainwindow.h"

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


}

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

Here ui_mainwindow.h is included and thats where the definition is. Forward declaration was only because the author didnt want ui_mainwindow.h to be included together with mainwindow.h. At least now I think so. Thank you man - this actually seems very useful!

EDIT : This is like the happiest moment of my day :D
Last edited on
Topic archived. No new replies allowed.