Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Qt needs allocate of child objects in the Heap?

Tags:

qt

class MyWidget : public QWidget { public:
    MyWidget( QWidget *parent=0, const char *name=0 ); };


MyWidget::MyWidget( QWidget *parent, const char *name )
        : QWidget( parent, name ) {
    QPushButton *quit = new QPushButton( "Quit", this, "quit" );
    quit->setGeometry( 62, 40, 75, 30 );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) ); 
} 

In the above code quit is allocated in Heap and it is necessary since it is child of MyWidget

Why does Qt needs allocate of child objects in the Heap?

like image 953
yesraaj Avatar asked Feb 25 '09 12:02

yesraaj


2 Answers

In your example quit doesn't have to be heap allocated.

This code compiles and executes fine:

struct MyWidget : QWidget 
{
    QPushButton quit;

    MyWidget()
    {
        quit.setGeometry( 62, 40, 75, 30 );
        quit.setFont( QFont( "Times", 18, QFont::Bold ) );
    }
};
like image 129
mxcl Avatar answered Sep 23 '22 04:09

mxcl


If I understand what you're asking correctly, I think it mostly boils down to tradition and example, with a little bit of header-dependency thrown in.

The alternative, of course, is to declare quit as a member variable of MyWidget. If you do this, then you would need to include the header file for QPushButton where MyWidget is declared, instead of in the implementation file. The example you gave also relies on the parent-relationship of QObjects to keep track of the memory for the button, and delete it on destruction, so it doesn't need to be specified as a member in the class.

I'm pretty sure you could change to stack allocation if you really wanted to.

like image 39
Caleb Huitt - cjhuitt Avatar answered Sep 21 '22 04:09

Caleb Huitt - cjhuitt