Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Cast to an interface that is not part of the base class

I have a series of classes representing "smart" map elements: MapTextElement, MapIconElement, etc. The classes are extending various Qt graphics item classes, but also provide common functionality, such as an abstract factory method that returns a property panel specialized for each class. I have declared these common methods in a pure virtual class, MapElementInterface. My classes then multiply-inherit the appropriate Qt base class as well as the interface:

class MapTextElement : public QGraphicsTextItem, public MapElementInterface
class MapIconElement : public QGraphicsItem, public MapElementInterface

So my class hierarchy looks kind of like:

         +-------------+    +-------------------+
         |QGraphicsItem|    |MapElementInterface|
         +-------------+    +-------------------+
                ^                   ^   ^
                |                   |   |
         +------+------+            |   |    
         |             |            |   |
+-----------------+   +--------------+  |
|QGraphicsTextItem|   |MapIconElement|  |
+-----------------+   +--------------+  |
     ^                                  |
     |                                  |
     +-------------------+        +-----+
                         |        |
                      +--------------+
                      |MapTextElement|
                      +--------------+

I am receiving a pointer to a QGraphicsItem from a Qt-provided method. In this case, I know that the pointer is not only QGraphicsItem, but also MapElementInterface. I want to treat the pointer as a MapElementInterface.

QList<QGraphicsItem*> selected = scene_->selectedItems();
if (selected.count() == 1) {
  // We know that the selected item implements MapEditorInterface
  MapElementInterface *element = SOME_CAST_HERE<MapElementInterface*>(selected[0]);
  QWidget *panel = element->GeneratePropertyPanel(property_dock_);
}

What is the proper cast to use? Or am I going about this completely the wrong way?

like image 844
Dave Mateer Avatar asked Jan 21 '23 18:01

Dave Mateer


1 Answers

With multiple inheritance, dynamic_cast is the only way, and check the return value against NULL.

like image 171
Frederik Slijkerman Avatar answered Jan 24 '23 07:01

Frederik Slijkerman