Consider following piece of code:
struct Fruit
{
Fruit() {}
virtual ~Fruit() {}
std::string name;
};
struct Banana : public Fruit
{
std::string color;
};
struct Pineapple : public Fruit
{
int weight;
};
here is my main() :
int main()
{
std::vector<std::unique_ptr<Fruit>> product;
product.push_back(std::unique_ptr<Banana>(new Banana)); //product[0] is a Banana
product.emplace_back(new Pineapple);
// I need to acess the "color" member of product[0]
std::unique_ptr<Banana> b = std::move(product[0]); // this doesn't work, why?
auto c = b->color;
}
in product[0]
I store a unique_ptr to Banana, why can't I assign it to a banana unique_ptr ?
You don't want ownership transfer, so cast only the pointer:
auto& banana = dynamic_cast<Banana&>(*product[0]);
auto c = banana.color;
dynamic_cast
might be replaced by static_cast
if you are really sure that Fruit
is really a Banana
.
In case your are wrong, static_cast
would lead to UB whereas you can check validity with dynamic_cast
(exception with cast to reference or null pointer with cast to pointer).