[Qt-interest] why parent widget in constructor?
Luca Ferrari
fluca1978 at infinito.it
Mon Apr 27 12:52:50 CEST 2009
On Sunday 26 April 2009 14:12:44 Donal O'Connor's cat walking on the keyboard
wrote:
> Java has garbage collection, but in C++ something must take responsibility
> for deleting objects.
It seems to me that this is more like a coding convention: having destructor
called from the last allocated variable to the first one, causes that a parent
initialized after a child widget will cause a double call to the destructor of
the child. So the following code in Java:
JButton button = new JButton();
JPanel container = new JPanel();
container.add( button );
must be translated into:
QWidget* container = new QWidget();
QPushButton* button = new QPUshButton( container);
or even in the manual case:
QWidget* container = new QWidget();
QPushButton* button = new QPUshButton( );
button->setParent( container );
but never to:
QPushButton* button = new QPUshButton( );
QWidget* container = new QWidget();
button->setParent( container );
because having the variables going out of scope causes button descrutor called
first by container one's and then by itself out of scope. Right?
So, if the above is right there is not a real technological motivation behind
having a parent pointer in the widget constructor, rather it is a mind-effort
to keep memory safe. Please correct me if I'm wrong.
However, another question that comes into my mind is why having the
setParent() method instead of an add one. I mean, why it is the child widget
that must specify which is its container, instead of having a container saying
which widget is one of its? This is more an OOP question, and after all the
child widget must notify the parent to add itself to its child list (or
whatever structure). So should not an add method be more clear?
Thanks,
Luca
More information about the Qt-interest-old
mailing list