Are C ++ polymorphic classes possible without any functions?

I am trying to create several classes that contain only data elements (no functions), but I would like them to be polymorphic - I mean that I will go around the objects with a pointer to the base class, and I need the ability dynamic_castto a specific derived type ( and have the resulting value be NULLif the instance is not of this type.)

As an example, I have an element:

struct Item {
    int x, y;
}

I also have an element that moves and the other is text:

struct MovingItem: virtual public Item {
    int speedX, speedY;
}

struct TextItem: virtual public Item {
    std::string text;
}

Presumably, I should use the virtual inheritance above, because I also need an element that moves and has text, but I only need one set of coordinates from the top level Item:

struct MovingTextItem: virtual public MovingItem, virtual public TextItem {
}

, dynamic_cast a Item * , , , .

void example(Item *i) {
    MovingTextItem *mti = dynamic_cast<MovingTextItem *>(i);  // error!
}

, , , , -.

, , type Item , dynamic_cast, , static_cast. ( , -, type .)

, ?

, , . MovingItem , TextItem , MovingTextItem - . , , , - , , .

+5
4

, vtable, dynamic_cast. no-op. ( , , , POD.)

( !), . . ? , , , , ( , ).

, , , , , - , - . , , , ?

, "", , . : "" - . . : " " ? ( , , .)

"" ( ): Position, Speed, Text Item. Item . " " . " ". Item ( ) . , . Position, -, , , . dynamic_cast .

ItemBase Position, Speed Text. . -, virtual...

+6

. dynamic_cast. . , .

+2

, . MovingItem . TextItem . , , MovingTextItem , MovingItem TextItem.

std::vector<Item*>. , .

?

, Item*, dynamic_cast , ( , , )? dynamic_cast? , dynamic_cast .

. : ?

., Item virtual, delete Item* . ++ . , - Item*.

dynamic_cast. , Item, dynamic_cast check .

Item ++ . , dynamic_cast, . , , Item , ++ dynamic_cast, , , .

, , dynamic_cast, - , .

+1

, Item , , :

enum ItemType {HasSpeed = 1, HasText = 2};
struct Item {
    int type;
    int x, y;

    int speedX, speedY;
    std::string text;
}

Then I just set type = HasSpeed | HasTextif both speed and text fields are working. Maybe a little old school, but it's a lot easier!

0
source

All Articles