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

I have a number of classes representing smart map elements: MapTextElement , MapIconElement , etc. Classes extend the various classes of Qt graphics elements, but also provide common functions, such as the abstract factory method, which returns a property panel specialized for each class. I declared these common methods in a pure virtual class, MapElementInterface . My classes are then multiplied - they inherit the corresponding 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 something like this:

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

I get a pointer to a QGraphicsItem from a Qt-provided method. In this case, I know that the pointer is not only a QGraphicsItem , but also a 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 right choice? Or am I completely wrong about this?

+4
source share
4 answers

With multiple inheritance, dynamic_cast is the only way and checks the return value for NULL.

+3
source

You have to be careful here because, given the chart, your pointer may point to a MapTextElement or MapIconElement. The only safe bet for you here is to go with dynamic casting. Or specify another way for yourself to determine the type of object.

+2
source

You can use MapIconElement and then MapElementInterface, or you can use MapTextElement and then MapElementInterface. You must choose a path (or dynamic down to check which path you are taking).

+1
source

Source: https://habr.com/ru/post/1315562/


All Articles