0

I'm trying to understand how Qt is handling instantiating objects of its widgets which are using dynamic memory allocation in user defined classes.

In below you can see main.cpp and part of a user-defined class "Foo" which comes from Qt installation example projects.
As a newbie I know that whenever we allocated dynamic memory we have to see the delete also somewhere in the code.The question is where is such delete to delete the dynamic memory which is allocated in Foo.cpp in below line?
QChartView *mychart= new QChartView();

main.cpp

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QMainWindow window;
    Foo *myobj = new Foo();
    window.setCentralWidget(myobj);
    window.resize(900, 600);
    window.show();
    return a.exec();
}

Foo.cpp

Foo::Foo(QWidget *parent) :
    QWidget(parent)
{
    QChartView *mychart= new QChartView();
...
Solook
  • 3
  • 5
  • It's unclear what you mean by "handle" here. You wrote that code in Foo.cpp, so you the programmer did(handled) the dynamic allocation. Please explain more specifically what you are wondering about. – nos Apr 23 '19 at 19:59
  • Whenever we allocate dynamic memory we have to make sure this memory is deleted somewhere in the code, by handle I meant this concept. But in example projects coming with Qt I don't see any `delete mychart` code. so I have assumed that Qt is handling such deletions, am I correct ? – Solook Apr 23 '19 at 20:09
  • That depends on what you're doing with that QChartView - e.g. if you add it to another widget, that widget takes responsibility for it(see https://stackoverflow.com/questions/2491707/memory-management-in-qt), but at least update your question with what you wrote in your comment, as that's what your question actually is about. – nos Apr 23 '19 at 20:21
  • question updated – Solook Apr 23 '19 at 20:40

1 Answers1

0
  1. Parent classes do not handle their children. Classes handle object they own. Any dynamically allocated objects owned by Foo should be cleaned up in Foo::~Foo().
  2. Likewise, dynamically allocated objects owned by QMainWindow are cleaned up in the destructor of QMainWindow. When you call window.setCentralWidget(myobj) you pass ownership of whatever is pointed to by myobj to window, so when window is destroyed, it deletes that object in its destructor. This in turns causes dynamically allocated objects owned by the object pointed-to by myobj to be cleaned up (see p.1)
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • Thanks! how the QmainWindow destructor ( which now have the ownership of `myobj` ) deletes `mychart` object in above code? by how I mean what could be the code in the QMainWindow destructor ? – Solook Apr 23 '19 at 20:31
  • @Solarisan "which now have the ownership of myobj" Actually it has ownership of the object pointed to by `myobj`, not `myobj` itself. I corrected the answer. The code could be `delete this->centralWidget` for example. – n. m. could be an AI Apr 23 '19 at 20:39