Dmitriy Kachko
Dmitriy Kachko

Reputation: 2914

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.

Upvotes: 1

Views: 483

Answers (3)

tmpearce
tmpearce

Reputation: 12683

The code works in Vis. Studio. Your problem may be that B is not a polymorphic class - I don't know why that would give you an error - but you could try making something in B virtual: virtual ~B(){} for example.

Upvotes: 0

shofee
shofee

Reputation: 2129

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

Upvotes: 3

Alok Save
Alok Save

Reputation: 206508

Why does the First example compile & Link cleanly while Second doesn't?

The first example compiles and links because:
It does not create an object of A,

A a1();

Declares a function a1() which takes no parameter and returns a A type.

While the Second example creates an object when new is called.

Note that the *undefined reference to vtable for A'* is a linking error and will only be emitted when a object ofclass A` is created. Hence only the Second example shows the error.

How to resolve the problem?
You need to provide definition for all virtual functions which you derive from QObject.

Upvotes: 3

Related Questions