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.