tags:

views:

463

answers:

4

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?

+2  A: 

I think the idea here is that Qt has it's own internal reference counting on most objects and if you pass them around, uses copy-on-write etc.

Could you be more specific in your question?

ypnos
+1  A: 

What other options are there? From the stack? How would Qt know when to allocate from stack and when from the heap? Things allocated from the stack will be gone as soon as the current function returns, so the lifetime of the object could be much shorter than the usage time. Imagine adding a node to a tree. The node will be used long after the current function has returned. This would lead to access to random memory, segmentation faults, core dumps, etc.

Aaron Digulla
A: 

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.

Caleb Huitt - cjhuitt
+1  A: 

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 ) );
    }
};
Max Howell