Why can't we create object in QT without the new
keyword? Usually we create pointer to an object, like this:
QLabel *ql=new QLabel(); ql->show()
But I want to create an object like this:
QLabel ql=QLabel(); ql.show()
Is it possible?
The thing is that the Qt controls (labels, buttons) are in a hierarchy (buttons belong to forms, for example). And the way Qt is implemented requires that when an object is destroyed, all objects that belong to it are destroyed as well.
If you place objects on a stack (that's how "create without new
keyword" is really called), they will be destroyed automatically. That's the property of C++, and it holds for all programs. Here's how the things would work if you allocated your label on the stack.
{
QLabel ql = QLabel(some_form);
ql.show()
} // scope ends, ql is deleted
delete some_form;
// ql will be deleted here as well
// but it's already dead!
// Program crashes!
Such stack allocation would mean that when you destroy the object the label belongs to, the label might already have been destroyed. It will make your program crash.
Actually, you can sometimes create objects on stack. In the main
function, you may allocate on stack your "main control" (usually it's the main window). The thing is that this object won't be destroyed during the program execution, so it can safely be on stack until main exits--i.e. the program terminates. Here's a quote from Qt tutorial:
#include <QApplication>
#include <QPushButton>
#include <QTranslator>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTranslator translator;
translator.load("hellotr_la");
app.installTranslator(&translator);
QPushButton hello(QPushButton::tr("Hello world!"));
hello.resize(100, 30);
hello.show();
return app.exec();
}
Change
QLabel ql=QLabel();
to
QLabel ql;
and read some C++ book.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With