Class Constructor



  • Could somebody please explain the syntax for this constructor, I mean what does it accomplish exactly. Sorry I am new to Qt and C++ and I've already read the docs but still need some clarification. As far as I understand MainWindow here declares QWidget as its parent, and the single column (":") is used for Initialization lists but I don't quite understand what this particular Initialization list does (especially the QMainWindow(parent) part, does it provide inheritance for MainWindow from QMainWindow class?). Thanks in advance.

    @MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)@


  • Lifetime Qt Champion

    Hi,

    @
    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent) << call base class constructor passing parent
    , ui(new Ui::MainWindow) << instanciate a new Ui::MainWindow object and assign it to the ui variable (well assign the pointer to the newly created object to ui which is a pointer to a Ui::MainWindow object)@

    Hope it helps



  • Thank you, it did, but can you also please tell me why it is needed.


  • Moderators

    Simple example :
    @
    class A {
    A() { ... }
    A(Type param) { ... }
    };

    class B : public A {
    B(Type param) {} //this will call A() implicitly
    B(Type param) : A(param) {} //this will call A(param)
    };
    @
    So it's needed to pass the parent pointer to the base class QObject so that it can do its magic with it. Otherwise the parent parameter would be ignored.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.