PDA

View Full Version : confusion with a STATEMENT used frequently



salmanmanekia
11th June 2008, 15:44
Hi,
May be the question ahead also comes in domain of Object Oriented ,i am confused with



class exclass :public QObject, public QGraphicsItem
{
Q_OBJECT

public:
exclass(QGraphicsItem *parent = 0);
};




#include "exclass.h"

exclass::exclass(QGraphicsItem *parent): QGraphicsItem(parent)
{

}




#include "exclass.h"

#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
exclass *mainScene = new exclass;
return a.exec();
}


I am confused with the statement

'exclass(QGraphicsItem *parent = 0); ' in the .h file and

'exclass::exclass(QGraphicsItem *parent): QGraphicsItem(parent){}' in the .cpp file

can anyone explain why the declaration as 'QGraphicsItem *parent' is necessary in the exclass constructor and why do we say it as 'QGraphicsItem *parent = 0 'in the .h file..
i avoided this question so far and just followed it but now i have to develop a QGraphicsItem parent and a child so i am confused with how to do it..

JimDaniel
11th June 2008, 16:01
Not sure how much you do or don't understand, but here are some ideas:

The parent/child object relationship metaphor is an intuitve way to build complex systems in a GUI.

In the header file, when you see something like, QGraphicsItem * parent = 0, that is referred to as a default parameter. It means that it can accept the parameter, but if you don't provide one, there is a default value to be passed in - in this case 0, or nothing, no parent.

//no parent
QGraphicsItem * parent_item = new QGraphicsItem();

//has a parent
QGraphicsItem * child_item = new QGraphicsItem(parent_item);

In the constructor implementation, because you are subclassing a QGraphicsItem, if your class ends up with a parent, then you pass it up to the base class, that is what you are doing here:

exclass::exclass(QGraphicsItem * parent): QGraphicsItem(parent){}

salmanmanekia
11th June 2008, 16:09
Thanks for the reply,but can you please elobrate more on this part :

" In the constructor implementation, because you are subclassing a QGraphicsItem,
if your class ends up with a parent, then you pass it up to the base class, that is what you are doing here:

exclass::exclass(QGraphicsItem * parent): QGraphicsItem(parent){} "

JimDaniel
11th June 2008, 20:54
Someone with more experience may need to step in to clarify, but the parent/child relationship of objects in Qt has to do with various things, one big thing being that the parent object controls when to destroy its children. If you subclass a Qt object, and it has a parent, then you need to pass that parent object to the base class as well, so it can call the right destructors up the chain. There may be other reasons too, and what I said may not be entirely accurate. Someone correct me if I'm wrong.