A QObject
is an object container. The objects it contains are called its children, the containing object is considered a parent to those children. This in itself says nothing about how and were the children are allocated. Let's look at some scenarios, in C++11:
void test() {
QObject aParent;
// children of automatic storage duration
QObject aChild1{&aParent}, aChild2;
aChild2->setParent(&aParent);
// children of dynamic storage duration
auto aChild3 = new QObject{&aParent};
auto aChild4 = new QObject;
aChild4->setParent(&aParent);
}
struct Parent : QObject {
QObject aChild5 { this };
QObject * aChild6 { new QObject };
QObject notAChild;
Parent() { aChild6->setParent(this); }
};
The test()
function demonstrates how an object can be a parent to some children of automatic and dynamic storage duration. The parent object can be given in the constructor or as an argument to setParent
method.
The Parent
class demonstrates that member objects can be children of the parent class, but not necessarily so. The member values are of automatic storage duration, but not all child objects are. The object pointed to by aChild6
is of dynamic storage duration. Since QObject
deletes all children in its destructor, the effective storage duration of the object at aChild6
is automatic: you don't have to worry about having to delete the object.