Thanks for the quick responses, much appreciated.
Yes, using pointers is neat, I’ll hopefully, eventually get used to thinking more elastically with pointers over time.
at first glance, my thought is to be careful about scope here, since once a variable, like “cat” is out of scope, the pointer that animals holds points to nothing.
Yes, one should watch out for that. Actually I was loking for something like this, as in your example:
> animals.push_back(new Animal());
> animals.push_back(new Cat());
> animals.push_back(new Dog());
I didn’t know that this was possible. How would I declare the vector type then? With ? And this would mean that vectors can hold multiple data types with different sizes, no? If I can hold the actual instances of objects in a vector with different sizes and types(they share the same base but they are different types I think, am I wrong?), well then that would be enough for me. I need to try it.
looking at this code. I remembered a question I had before – is there any way to get the type out of the vector? ie, to know that animals is a cat, or is that something you have to remember.
What I do about this is that I declare a variable in class definitions called “myType”, give a number to it and then check that variable to determine the type. It might be a lame solution maybe, I don’t know but works for me.
All these lead me to another question: Since I’m used to the leisure of the automatic garbage collector in Java/Processing, now I’m a bit paranoid about memory management and leaks. What would be the correct way to delete an object instance from a vector in the proposed solutions?
Zach, in your solution(pushing back with new), I guess that the vector will be holding the actual instances so, if I use the erase method on a vector, I think it would free the resources for the instance automatically. Is this right?
What if the class itself has dynamically allocated arrays inside? Do I need to explicitly free them in the destructor?
And how would I go for freeing the object instance if I’m holding the pointers to objects in the vector as proposed by companje?