tags:

views:

259

answers:

5

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?

+15  A: 

Change

QLabel ql=QLabel();

to

QLabel ql;

and read some C++ book.

kemiisto
+2  A: 

You can create Qt objects from stack (without new) but those objects are automatically deleted when they fall out of scope. For example:

void doSomething()
{
    QLabel ql; 
    ql.show()
} // scope ends, ql is deleted

And that's how C++ works, it's not a Qt specific feature.

Roku
+2  A: 
QLabel ql;

creates a QLabel on the stack. Note that it just lives until the current scope exits.

DerKuchen
It's only created on the stack if this code is in a function. As a global it will be created on the heap.
PiedPiper
+10  A: 

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();
 }
Pavel Shved
There is a brief explanation from Qt on this as well, here: http://doc.qt.nokia.com/4.6/objecttrees.html
Arnold Spence
A: 

Such code:

QLabel ql=QLabel();    ql.show()

won't compile, because QLabel inherits QObject. And you can't make a copy of QObject, because its copy constructor and assignment operators are disabled: http://doc.trolltech.com/4.6/qobject.html#no-copy-constructor

However,

QLabel ql;

will work.

comb