Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declare same namespace in two different headers then including them in one cpp

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

like image 610
Shady Atef Avatar asked Jan 12 '14 22:01

Shady Atef


2 Answers

  1. It is merged.

  2. 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.

like image 147
Matteo Italia Avatar answered Oct 18 '22 22:10

Matteo Italia


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.

like image 30
Dietmar Kühl Avatar answered Oct 18 '22 21:10

Dietmar Kühl