how makes this work ?
I want to use a vector of multiple types (research, add, delete) for an inventory management (Potions, Weapons, etc.. all derived from virtual class Item).
I simplify the problem here : I have a vector containing Item (Base class) and Weapons (Derived class). For memory management issues, i prefered using unique_ptr but didn't a way to return it or use it properly.
Example Below :
// UniquePointerAndPolymorphism.cpp : Ce fichier contient la fonction 'main'. L'exécution du programme commence et se termine à cet endroit.
//
#include <iostream>
#include <vector>
class Item
{
protected:
std::string name_;
public:
Item(std::string name) :name_(name) {};
virtual std::string getName() { return "b_" + name_; };
};
class Weapon : public Item
{
public:
Weapon(std::string name) : Item(name) {};
std::string getName() override { return "d_" + name_; };
};
std::vector<std::unique_ptr<Item>> elements;
std::unique_ptr<Weapon> getAnElement_uniquePointer(int i)
{
/*
*
* How to return unique pointer from the vector ?????
*
*/
return std::make_unique<Weapon>("returned");
}
Weapon* getAnElement_rawPointer(int i)
{
if (auto oneElement = dynamic_cast<Weapon*>(elements[i].get()))
{
return oneElement;
}
else
{
return nullptr;
}
}
int main()
{
elements.push_back(std::make_unique<Weapon>("1"));
elements.push_back(std::make_unique<Item>("2"));
elements.push_back(std::make_unique<Weapon>("3"));
Weapon* rptElement = getAnElement_rawPointer(2);
std::cout << rptElement->getName() << std::endl;
std::unique_ptr<Weapon> uptElement = std::move(getAnElement_uniquePointer(0));
std::cout << uptElement->getName() << std::endl;
}
So I have a few questions :
- Even if it seems to not be the problem, is Polymorphism compatible with smart pointers ?
- Was returning a raw pointer the only solution ?
- Do I have to use shared_pointer to use it in the vector and in another part of my programm ?
- Is there a way to return a reference ?
Thanks. Sebastien