I am working on my c++ assignment and I try to use polymorphism in my program. in my program i want to store the pointer of some objects in a pointer vector right after they are constructed:
entities.push_back(&Invader4());
entities.push_back(&Invader3());
entities.push_back(&Invader2());
entities.push_back(&Invader1());
entities.push_back(&Invader0());
class Invader inherit class Entity, but when I try to access the element in entities, an accesss violation occurs. do i have to declare another Invader type vector to store these objects first?
You’re taking the address of a temporary, which is illegal (undefined behavior to be exact). Just dynamically allocate the memory:
don’t forget to delete the memory in the vector when you’re done.
Also, take a look into smart pointers, might be more appropriate here.
Edit: by deleting, I mean
when you’re done with the vector.