Qt World Summit: Register Today!

Question on initialization of mainwindow

  • I am learning a Qt example for Dock Widgets. In the .h file the mainwindow has a default constructor that does not have any arguments, though the the mainwindow includes a member called textEdit, along with other member widegets.


    QTextEdit *textEdit;

    However, in the implementation the mainwindow constructor includes textEdit in the initilizer list, even though it is not an argument for the mainwindow constructor. At the same time other member widgets are not included in the list. Can you help me understand this?

    : textEdit(new QTextEdit)

  • Moderators

    There are 4 pointers in that class: textEdit, customerList, paragraphsList and viewMenu. All of them need to be initialized somewhere.

    The first one is initialized in the initialization list of the class constructor as you mentioned. Using initialization list doesn't require you to init the member via a parameter. It can be initialized from any value, in this case it's a new statement. For example:

    class Foo {
        Foo() : bar(42) {}             //initializing bar via value
        Foo(int param) : bar(param) {} //initializing bar via param
        Foo() { initBar(); }           //initializing bar via member function
        void initBar() {  bar = 42; }
        int bar;

    The example uses the first type of initialization for textEdit.

    All the other pointer members are initialized in the MainWindow::createDockWindows() which is called from the constructor's body. It's the third type of initialization from the example above.

Log in to reply