title: C++ - Why do I create these widgets on the heap?
body: <p>When creating a GUI with C++ and Qt you can create a label for example like this :</p>
  
  <pre><code>QLabel* label = new QLabel("Hey you!", centralWidgetParent);
  </code></pre>
  
  <p>This creates the object on the heap and will stay there until I either delete it manually or the parent gets destroyed. My question now is why do I need a pointer for that? Why not create it on the stack?</p>
  
  <pre><code>//Create a member variable of Class MainWindow
  QLabel label;
  
  //Set parent to show it and give a text so the user can see it
      QWidget* centralWidget = new QWidget(this); //Needed to add widgets to the window
      this-&gt;setCentralWidget( centralWidget ); 
      label.setParent(centralWidget);
      label.setText( "Haha" );
  </code></pre>
  
  <p>This works fine, I can see the label and it did not vanish.</p>
  
  <p>We use pointers in C++ to let something live longer so we can use an object in various scopes. But when I create a member variable, won't it stay until the object gets destroyed?</p>
  
  <p>Edit:
  Maybe I didn't clarify it enough. This is the MainWindow class:</p>
  
  <pre><code>class MainWindow : public QMainWindow
  {
      Q_OBJECT
      QLabel label; //First introduced here...
  
  public:
      MainWindow(QWidget *parent = 0);
      ~MainWindow();
  };
  
  //Constructor
  MainWindow::MainWindow(QWidget *parent)
      : QMainWindow(parent)
  {
      QWidget* centralWidget = new QWidget(this);
      this-&gt;setCentralWidget( centralWidget );
      label.setParent(centralWidget);
      label.setText( "Haha" );
  }
  </code></pre>