polymorphism - C++ Calling a child class function from a base class when I don't know the childs' type -



polymorphism - C++ Calling a child class function from a base class when I don't know the childs' type -

i have inventory stores 'inventoryitem's.

struct inventoryitem{ item* item; unsigned int quantity;}; std::vector<inventoryitem> m_items;

i add together items following, m_inventory.additem(bandage);

but when seek phone call bandages's use() function has been derived item base of operations class, calls item class use() funtion instead.

it has been declared in item class so,

// .... public: // .... virtual void use(player&){} // ....

it has been declared in bandage class so,

// .... class bandage : public item{ public: // .... virtual void use(player&); // ....

it has been defined in bandage class so,

void bandage::use(player& player) { player.heal(35); }

when effort phone call use() function of item, instance, m_items.at(i).item->use(*m_player);

it calls base of operations class 'item' use() function, rather 'bandage' use() function.

edit: here additem function,

void inventory::additem(const item& item) { if ((m_items.size() < m_capacity)) { bool founditem(false); (auto invitem : m_items) { // if item exists, lets increment quantity if (invitem.item->getid() == item.getid()) { founditem = true; if (invitem.quantity < invitem.item->getinventoryquantitylimit()) { ++invitem.quantity; } } } if (!founditem){ m_items.push_back(inventoryitem{ new item(item), 1 }); } } }

the problem in additem() function, more exactly here:

m_items.push_back(inventoryitem{ new item(item), 1 });

the pointer item* in inventoryitem ends pointing item, , not objects derived item, when item is derived object. look new item(item) doesn't create derived object, invokes (default if haven't written it) re-create constructor of item derived object item parameter. creates item object on heap, returning pointer it.

you improve off mill method creates required items, , rid of raw pointers in favor of std::shared_ptr (or std::unique_ptr, although here std::shared_ptr better).

c++ polymorphism base-class

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -