Search code examples
c++qtmultiple-inheritanceqobject

QObject multiple inheritance and operator new


Stuck with this weird question

Why following code is OK for g++

#include <QObject>

class B {
public:
  B(){}
  ~B(){}
};

class A : public QObject, public B {
  Q_OBJECT
public:
  A(QObject * parent = 0 ) : QObject( parent ), B() {}
  ~A(){}
};

int main(int argc, char *argv[])
{
  A a1();
  //A * a = new A();
  //delete a;
  return 0;
}

and this can not be compiled

/*... the same class definitions as above */    

int main(int argc, char *argv[])
{
  //A a1();
  A * a = new A();
  delete a;
  return 0;
}

//error: undefined reference to `vtable for A'

I mean what to do to make the second good as well?

PS Well I put everything in separate files, and it works fine. So it is a matter of Q_OBJECT macros, I think.


Solution

  • If you define a QObject-derived class, build an application, and realize you forgot to add the Q_OBJECT macro, and you add it later, it is important that you qmake to explicitly update the Makefile. Furthermore, to be safe, I recommend a make clean to get rid of old files. make is not smart enough to clean up all of its generated files under such circumstances, and this is an issue that often causes headaches to new Qt developers.

    For more information about this error message, see

    http://cartan.cas.suffolk.edu/oopdocbook/html/commonlinkererrors.html#undefinedreftovtable