GUI objects creation/deletion

Hi, I have a basic query regarding GUI Objects (Labels, Combo Boxes etc) creation and deletion in a Dialog Box / Window. If I have the following code:
1
2
3
4
5
6
7
8
9
10
void MyWindow::someFunction() {
  Label* myLabel = new Label(this); // how is it different from just "new Label";
  //some code using myLabel;
  // assuming I do not delete myLabel.
  // and call nextFunction on the click of an existing button
}

void MyWindow::nextFunction() {
  // Here I want to remove the existing Objects from my Window and add new items.
}


1. Will myLabel (the object, not the pointer) be visible to me in the nextFuntion?
2. Is it necessary to call delete for the objects that I created in someFunction or are they cleaned up automatically by the compiler?

I am using Qt Creater as the IDE. Any help/clarification shall be appreciated.

Thanks
Last edited on
In Qt, a child is normally owned by the parent. This is the point of passing the this pointer to the child instance. It has been a while since I used Qt, but in general cases of widget/windowing toolkits, the idea behind passing the parent instance to the child will be something similar to this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Child constructor
Child::Child(BaseWidget* parent)
{
    if (parent != nullptr)
        parent->RegisterChild(this); // assume RegisterChild just adds the child instance to the parent's list
}

// On Parent's destructor
BaseWidget::~BaseWidget(void)
{
    // iterate through list of children then call delete
    for (auto* child : m_children) // m_children is the list of children
        delete (child);
}


Of course the actual implementation is more complicated than the snippet above, but it should give you the idea. The point is that instance ownership must be respected. So to answer your 2nd question:
Is it necessary to call delete for the objects that I created in someFunction or are they cleaned up automatically by the compiler?

You need to know how your objects are created and who owns them if they are in the heap. In some cases, it maybe a good idea to use smart pointers when the instantiated object is just going to be used locally.

For your 1st question:
Will myLabel (the object, not the pointer) be visible to me in the nextFuntion?

Based on your code snippet, it is allocated on the heap, thus it is visible by means of accessing it directly through its address. If the myLabel is owned by the this instance, then you maybe able to access by other means. You will need to check Qt documentation about this.
Hey thanks for the help vince1027.

So if I have understood correctly, a child should be created using "this" pointer when we want to include the child in the parent's list of objects. The children get destroyed along with the parent.

For interfunction visibility/Auto-deletion I will have to check out the concept of "Smart Pointers" and how the objects are allocated on the "heap".
Topic archived. No new replies allowed.