I have a simple structure of abstract class Animal
and a class Dog
derived from it. I want to keep different Animals
in Cage
using a pointer to Animal
. I would like to be able to create a Dog
inside of a Cage
constructor but it creates a temporary object which I can't point to:
class Animal
{
public:
Animal() {}
virtual ~Animal() {}
};
class Dog: public Animal
{
public:
~Dog() {}
};
class Cage
{
public:
const Animal* animal;
Cage(Animal *anim): animal(anim) {}
};
int main()
{
Dog doggy;
Cage cage(&doggy); //works fine
Cage new_cage(&Dog()); //error: taking address of temporary [-fpermissive]|
}
Is there any way to change the code, e.g. Cage
's constructor, so that the object created in it's constructor would be non-temporary?
EDIT: It seems like it could be done using dynamic allocation but this question was marked as a duplicate of this question
Why lifetime of temporary doesn't extend till lifetime of enclosing object? , although it's a different question. I asked for any way to make that happen and not for extending a lifetime of a temporary. I would be grateful to πάντα ῥεῖ if he could explain how my question has an answer in this one's answers.