
Originally Posted by
rookee
Someone please help me understand the syntax and what is happening in these below lines of the code from the link
http://ldc.usb.ve/docs/qt/tutorial-t5.html. Thanks in advance.
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = 0); <== is MyWidget a class a function or a constructor?
};
MyWidget::MyWidget(QWidget *parent): QWidget(parent) <== What is this syntax and what does it mean?
If you review the chapters explaining classes in c++, you will know everything here.
basically
{
public:
};
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = 0);
};
To copy to clipboard, switch view to plain text mode
you have a class named MyWidget, which inherits from QWidget. so when you do create your classes, most of the time you also define a constructor for it.
and the constructor has the name of your class, without any return type, It can take any number of parameters, including none!
but since you are inheriting from something else, in order to get things working, if the base class needs something , you need to give what it needs
and here we get it from the user and passes it to the base class's constructor.
thats why we have a QWidgets* parameter for our constructor,
Now we could also have the definition written here as well, which would look like this :
{
public:
{
....
}
};
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = 0) :QWidget(parent)
{
....
}
};
To copy to clipboard, switch view to plain text mode
This is kind of equivalent to
{
public:
{
}
};
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = 0)
{
QWidget(parent)
}
};
To copy to clipboard, switch view to plain text mode
And what is trying to say is that, first build the base part, gives it what ever it needs to properly initialize, and then continue with my specific customization.
(and by the way, the second snippet which I gave you is not valid, I just wrote it as a hint of what happens here , you need to use the first style for initialing the base constructors )
and finally, it is good programming practice to separate the class signature definition and their implementation .
so to do that we can also do it like this :
this is class definition (signature if you will )
{
public:
};
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = 0);
};
To copy to clipboard, switch view to plain text mode
and this is the implementation details
{}
MyWidget::MyWidget(QWidget *parent): QWidget(parent)
{}
To copy to clipboard, switch view to plain text mode
the first part says, the remaining belongs to the MyWidget class
you can see two simple example of both cases here :
http://ideone.com/4XXZJw
http://ideone.com/B4CtyX
Hope this helps
Bookmarks