4

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

friede
  • 137
  • 8
  • As the answers indicate, this is not a problem specific to Qt or the QDialog class. The syntax for calling a constructor that accepts no arguments in C++ is different than it is in, say, C#. You have to omit the parentheses, otherwise the compiler thinks you're declaring a function. – Cody Gray - on strike Jun 25 '11 at 14:07
  • 1
    Btw, you are misusing the term `explicit constructor`. Here's something to read: http://msdn.microsoft.com/en-us/library/h1y7x448.aspx – Armen Tsirunyan Jun 25 '11 at 14:11

2 Answers2

8

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

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
2
QDialog dialog;

is the correct syntax to create a QDialog on stack with the default constructor.

Mat
  • 202,337
  • 40
  • 393
  • 406