18

Lets say I have a two classes:

class A : public QObject {};
class B : public QObject {};

then I go

QObject *a = new A();
QObject *b = new B();

now, how do I make sure that "a" is an instance of class A, and "b" is an instance of class B?

currently I do something like this:

if (a->inherits(A::staticMetaObject.className())) {
...
} else if (a->inherits(A::staticMetaObject.className())) {
...

is there a better way?

sshilovsky
  • 958
  • 2
  • 9
  • 22
ak.
  • 3,329
  • 3
  • 38
  • 50

1 Answers1

37

You can use qobject_cast<MyClass*>(instance) on QObject derived classes and check the return value. If instance cannot be cast to MyClass*, the return value will be NULL.

erelender
  • 6,175
  • 32
  • 49
  • 1
    Well.. looking into inherits function source shows that internally it uses qobject_cast to verify object type – ak. Jan 05 '10 at 14:07