Holla , In auto-generated Qt 5 project files by QtCreator There is a declaration of a namespace called Ui in two separate headers and both of them are included in one cpp file
//mainwindow.h
namespace Ui {
class MainWindow;
}
//ui_mainwindow.h
namespace Ui {
class MainWindow: public Ui_MainWindow {};
int x;
}
//mainwindow.cpp
#include "ui_mainwindow.h"
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
I wonder what happens to the namespace ? is it merged and why this is not considered as redefinition of Class MainWindow ? Thanks in advance.
Thanks for your answers & I found this article about headers including
It is merged.
The first class MainWindow;
is a forward declaration and it's very much intentional; it's used to tell the compiler "there is a class named like that, later I'll define it".
It is useful since a forward declaration allows you to declare pointers and references without having the full class definition yet, thus allowing you to break dependency circles between classes and keeping down the headers to be included if they aren't really necessary. The forward declaration is later (optionally) replaced by the usual full class definition.
You can open namespaces as often as you want. The declarations are simply merged. That works the same way as it works for the global namespace already: you can have multiple headers declaring names in the global namespace, too. The declarations seen is just the union of all declarations.
With respect to Ui::MainWindow
, the mainwindow.h
file doesn't provide a definition. It only provides a declaration. You can declare a class as often as you want in a translation unit. The ui_mainwindow.h
file provides a definition of Ui::MainWindow
. Within one translation unit you are allowed only one definition of a class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With