Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QDialog explicit constructor without argument - how to use correctly?

I experienced this with a derived class, but it's the same with QDialog base class:

when I do

QDialog dialog();
dialog.exec();

the compiler complains

J:\...\mainwindow.cpp:-1: In member function 'void MainWindow::on_viewButton_pressed()':
J:\...\mainwindow.cpp:72: Fehler:request for member 'exec' in 'dialog', which is of non-class type 'QDialog()'

This has something to do with the constructor being used, because when i do

QDialog dialog(0);
dialog.exec();

the code compiles without errors. This is also working:

QDialog *dial = new QDialog();
dial->exec();

So. Is it because of an explicit constructor?

Documentation says it's defined as

QDialog::QDialog ( QWidget * parent = 0, Qt::WindowFlags f = 0 )

So shouldn't the first two examples do exactly the same? And why is the compiler complaining on the second line, not the one with the constructor.

Thanks for enlightenment, hints to further readings on the topic very welcome

like image 674
friedemann Avatar asked Dec 28 '22 18:12

friedemann


1 Answers

QDialog dialog();

This declares a function named dialog that takes nothing and returns a QDialog

If that surprises you, suppose you named your variable f instead of dialog. What we get?

QDialog f();

Looks more like a function now, doesn't it? :)

You need

QDialog dialog;

Always, when something can be interpreted as a declaration and something else, the compiler always solves the ambiguity in favor of a declaration

like image 120
Armen Tsirunyan Avatar answered Mar 31 '23 23:03

Armen Tsirunyan