[SOLVED] Constructor difference



  • Hey, could someone explain what is the difference between
    @
    explicit MainWindow(QWidget *parent = 0)
    : QWidget(parent) { }@

    and
    @explicit MainWindow(QWidget *parent = 0);@

    At the first example, what could I write inside of the { } ?


  • Moderators

    I understand you're a c++ novice? Maybe it would be better to grab a book or a tutorial on classes.

    Anyway, both of these together define a constructor.

    You have an error in the first part. there should be no explicit keyword here and no = 0 in the parameter list. These go only into the declaration in the header (the second snippet).

    The first one is a definition. It goes into the .cpp file. It contains the actual code of the function. That's what you put in the {}. I can't tell you what exactly that is because I don't know what you're program is supposed to do ;) It can also initialize member variables (you heve none here) and call the base class constructor (here it's QWidget(parent)).

    The second one is a declaration. You put it in a header and it describes what name and parameters a function has. It can also define default arguments values.



  • Actually, both of these are from header files... When I create class in Qt it uses second example, but I've seen in some codes on the internet where people are using first example...


  • Moderators

    Oh, then someone is doing "the wrong thing"™ and is putting his code in the header, which you shouldn't do. That's usually good for examples though as it's shorter so you will find it on forums and such ;)

    Basically you can do either this (which is what you should):
    @
    //class.h
    class Foo {
    public:
    Foo();
    };

    //class.cpp
    Foo::Foo() {}
    @
    Or this:
    @
    //class.h
    class Foo {
    public:
    Foo() {}
    };
    @
    The second one is shorter but will not compile if you happen to include that header in multiple places.



  • I understand now, thank you...


Log in to reply
 

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