0

I wrote a simple test as follow:

#include <QCoreApplication>
#include <QObject>

class Foo : public QObject
{
   Q_OBJECT
};

class foo1
{
};

int main(int argc, char* argv[])
{
QCoreApplication a(argc, argv);
Foo f;
return a.exec();
}

Which gives me an error:

error: undefined reference to `vtable for Foo':

However, when I change Foo f to Foo f(), it complies without any error.
So my question is what is the different between f and f()?

Dr.jacky
  • 3,341
  • 6
  • 53
  • 91
himlen
  • 1
  • 1

2 Answers2

2

Adding the parenthesis makes it a function declaration. No object is actually created, so the error doesn't happen.

Foo f; //declaration of variable of type Foo

Foo f(); //declaration of function taking no args and returning Foo

The undefined reference to vtable for Foo error is because you added a call to Q_OBJECT without running qmake again. Once it's run, the error should disappear.

Weak to Enuma Elish
  • 4,622
  • 3
  • 24
  • 36
  • 1
    I have tried cleaning project and running qmake again, but the error still came when I used Foo f – himlen Mar 14 '16 at 03:06
1

This error is caused of the class extended QObject to be declared in main.cpp, so just add the line #include "main.moc" before (or after) your main method. But in the next time define a separate h/cpp-file for QObject extended classes.

Alexander Chernin
  • 446
  • 2
  • 8
  • 17