Converting a pointer for a base class into an inherited class

Posted by Shawn B on Stack Overflow See other posts from Stack Overflow or by Shawn B
Published on 2010-03-26T14:31:00Z Indexed on 2010/03/26 14:33 UTC
Read the original article Hit count: 366

Hey,

I'm working on a small roguelike game, and for any object/"thing" that is not a part of the map is based off an XEntity class. There are several classes that depend on it, such as XPlayer, XItem, and XMonster.

My problem is, that I want to convert a pointer from XEntity to XItem when I know that an object is in item. The sample code I am using to pick up an item is this, it is when a different entity picks up an item it is standing over.

void XEntity::PickupItem()
{
    XEntity *Ent = MapList; // Start of a linked list

    while(true)
    {
        if(Ent == NULL) { break; }

        if(Ent->Flags & ENT_ITEM)
        {
            Ent->RemoveEntity(); // Unlink from the map's linked list

            XItem *Item = Ent // Problem is here, type-safety

            // Code to link into inventory is here

            break;
        }

        Ent = Ent->MapList;
    }
}

My first thought was to create a method in XEntity that returns itself as an XItem pointer, but it creates circular dependencies that are unresolvable.

I'm pretty stumped about this one. Any help is greatly appreciated.

© Stack Overflow or respective owner

Related posts about c++

Related posts about object-oriented