Say I have
Animal animals[100];
And now, at run-time, I want to initialize one of these to be a new instance of Cat
, a subclass of Animal
. How do I do this? I thought maybe I could do
animals[0] = Cat("Fluffy")
but this doesn't seem to work. My understanding of how a constructor works in C++ is that space for the object is allocated, and then a pointer to that space is passed to the constructor function (as this
). In particular, the constructor works even if that space contains any arbitrary garbage data. So it seems to me that even if animals[0]
already contains data initialized by the constructor of Animal
or whatever else was occupying that slot beforehand, it should be possible to just call the constructor of Cat
on that space and have it work exactly as if it were a totally "fresh" object. How can I achieve this?
For example, the following code should print "Fluffy", but it prints "Anonymous".
#include <stdio.h>
class Animal
{
public:
virtual char const *get_name() { return "Anonymous"; };
};
class Cat : public Animal
{
char const *name;
public:
Cat(char const *name) { this->name = name; }
char const *get_name() { return name; }
};
Animal animals[100];
int main()
{
animals[0] = Cat("Fluffy");
printf("%s\n", animals[0].get_name());
return 0;
}