Consider the following C++ classes:
// An abstract fruit that can be sliced
class AbstractFruit
{
public:
virtual void Slice() = 0;
};
// A lemon (concrete implementation of AbstractFruit)
class Lemon : public AbstractFruit
{
int size; // small medium large
public:
Lemon(int size) : size(size) {}
virtual void Slice() override { /* slice it */ }
};
// A pie uses a fruit reference
class Pie
{
AbstractFruit& fruit;
public:
Pie(AbstractFruit& fruit) : fruit(fruit) {}
};
This all works fine.
For backwards compatibility reasons, the Pie API needs to have a constructor that creates a lemon pie:
Pie(int size) : fruit(Lemon(size)) {}
This doesn't work. To the best of my understanding, I'm creating a new Lemon instance in the parameter list of the constructor and initializing the fruit reference with it. But, the Lemon instance gets destructed immediately after that, leaving the fruit reference pointing to a destroyed object.
What's the best way to make this work?
I understand I could switch the Pie to use a pointer instead of a reference, but I'd like to use a reference if possible.
fruit(fruit)is so unreadable