I'm struggling with casing a subclass as a superclass to store in a vector of super class pointers. The objective is to have a vector of ContainerObjects which can be both bins and boxes.
This is a barebones example - in my code I am passing in a definition of stuff to store in the box and then add the the box to my inventory. That part is working fine, but its the adding the box to the inventory which is defeating me.
typedef std::unique_ptr<ContainerObject> U_ContainerObjectPtr;
typedef std::unique_ptr<Box> U_BoxPtr;
typedef std::unique_ptr<Bin> U_BinPtr;
class DoingWork
{
private:
StorageArea area;
public:
void boxItem( ItemData data)
{
U_BoxPtr newBox = std::make_unique<Box>(data);
area.addContainer( newBox );
}
}
class StorageArea
{
vector<U_ContainerObjectPtr> myStorageArea;
addContainer( U_ContainerObjectPtr container)
{
myStorageArea.push_back(container);
}
}
class ContainerObject
{
}
class Box : ContainerObject
{
Box( ItemData data)
{
// store the data in the box
}
}
// Another container type
class Bin : ContainerObject
{
}
The error I am getting is "No suitable user-defined conversion from U_BoxPtr to U_ContainerObjectPtr" on the call to addContainer() in boxItem() which is understandable. I'm not sure what I need to do to resolve this, or even if this is actually possible.
Reasonably new to C as well.
CodePudding user response:
Firstly, you should make your inheritance publicly.
class Box : ContainerObject -> class Box : public ContainerObject
class Bin : ContainerObject -> class Bin : public ContainerObject
Secondly, std::unique_ptr implies only one owner, so it has no copy constructor/asignment only move constructor/asignment.
So you should do the following replacements:
area.addContainer(newBox); -> area.addContainer(std::move(newBox));
myStorageArea.push_back(container); -> myStorageArea.push_back(std::move(container));
The whole code looks like this:
#include <memory>
#include <vector>
struct ItemData
{
};
class ContainerObject
{
};
using U_ContainerObjectPtr = std::unique_ptr<ContainerObject>;
class Box : public ContainerObject
{
public:
Box(ItemData data)
{
// store the data in the box
}
};
// Another container type
class Bin : public ContainerObject
{
};
using U_BoxPtr = std::unique_ptr<Box>;
using U_BinPtr = std::unique_ptr<Bin>;
class StorageArea
{
std::vector<U_ContainerObjectPtr> myStorageArea;
public:
void addContainer(U_ContainerObjectPtr container)
{
myStorageArea.push_back(std::move(container));
}
};
class DoingWork
{
private:
StorageArea area;
public:
void boxItem(ItemData data)
{
U_BoxPtr newBox = std::make_unique<Box>(data);
area.addContainer(std::move(newBox));
}
};
