Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly check if an object implements an interface

I want to implement custom behavior for certain objects.

For that, have my items (inheriting from QGraphicsItem) implement some interface.

class SomeParentItem 
{ 
    SomeParentItem(bool x) { x = true; } 
    void function1() {}
};
class SomeInterface
{
    virtual void function2() = 0;
};
class XYZItem : public QGraphicsXYZItem, public SomeParentItem, public SomeInterface
{
    XYZItem(bool x):SomeParentItem(x) {}
    virtual void function2() { x = false; }
};
class MPQItem : public QGraphicsMPQItem, public SomeParentItem
{
    MPQItem (bool x):SomeParentItem(x) {}
};

From outside, I was thinking that i just do

SomeInterface* item1 = dynamic_cast<SomeInterface*>(item);
if(item1 == NULL)
    item->function1(); 
else
    item1->function2();  

Unfortunately this crashes... usually... so I was creating a flag to test, and if the flag was true, only then dare to cast.

But I kept thinking, it shouldn't crash. So I got brave and tried it again, this time in a QWidget child. Instead of crash I got

QWidget::insertAction: Attempt to insert null action

It is the test if(item1 == NULL) that gives that message...

How do I check correctly if my item implements SomeInterface ?

Note: item cannot be null.

like image 571
Thalia Avatar asked Jul 07 '15 17:07

Thalia


People also ask

How do you check if an object implements an interface?

Use a user-defined type guard to check if an object implements an interface in TypeScript. The user-defined type guard consists of a function, which checks if the passed in object contains specific properties and returns a type predicate.

How do you check if a class is an interface?

isInterface() method The isArray() method of the Class class is used to check whether a class is an interface or not. This method returns true if the given class is an interface. Otherwise, the method returns false , indicating that the given class is not an interface.

Can an object implement an interface?

If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface. By casting object1 to a Relatable type, it can invoke the isLargerThan method.


1 Answers

There may be a compiler switch which disables run-time-type-information, in which case it would explain behaviour. Otherwise item1 should only be non-null, if the dynamic_cast worked

like image 130
mksteve Avatar answered Oct 02 '22 07:10

mksteve