c++ – How does the class constructor declaration in Qt work?

Question:

I work with C and a little bit of assembly , on Atmel AVR microcontrollers. I'm trying to understand how the Qt framework extends C++.

I created a new project with Qt Creator (Widgets), and generated the following code:

MainWindow::MainWindow(QWidget *parent) : 
    QMainWindow(parent), //<-- qual a relação do ponteiro acima e o parâmetro passado aqui?
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

[1] What's on the first line after the : operator? is it some kind of inheritance? to my eye it looks like an initialization type, could there be this after the : operator?

[2] When constructing the object in the _main.cpp_ file, where are the constructor arguments?

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w; //<-- Onde estão os argumentos?
    w.show();

    return a.exec();
}

If it can be explained a little more fully, I would appreciate it.

Answer:

You got it right, it has to do with inheritance, at least in the first case. This is a boot list . In this case, the MainWindow constructor is calling the QMainWindow constructor, obviously passing the parameter it received as an argument to this constructor. This has to do with the way the argument needs to be passed which is otherwise not so intuitive. And if I'm not mistaken with the boot order, but I could be confusing languages.

It also assembles a member called ui by initializing it with an existing MainWindow class in the Ui namespace . This is already a composition. Note that it does this before it actually starts executing the code inside the constructor. Although the second has no advantages of being there. I could write like this:

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

I put it on GitHub for future reference .

On the second question, there is no argument, w will be initialized with a constructor without arguments that must also exist in the class or it is initializing the window with a default value , as Luiz Vieira said in the comments below. The main window doesn't have a parent control, doesn't need to pass anything to it, or pass a null value that indicates the absence of a parent window. This can be achieved with another feature of the language that the parameter takes on a value in the absence of an argument. So a constructor with no arguments like the one shown above could be calling a constructor with parameters, as long as there is a default value set in them.

Scroll to Top