Sign in to follow this  

Vector template question

This topic is 2835 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a class called MovingEntity. From that Guard and one or two others will be inherited. So im doing a collision avoidance algorithm and i want to pass in a vector of all the characters on the map so the algorithm can check for a collision. So i tried passing in a vector of movingEntities, as they all inherit from that and the info i need is in that class, things like position. But im getting an error. error C2664: 'Guard::Update' : cannot convert parameter 1 from 'std::vector<_Ty>' to 'std::vector<_Ty>' from for (unsigned int i=0; i<Guards.size(); ++i) { Guards[i]->Update(Guards, time); } So Guards are inherited from movingEntity, Guards is a list of Guards and Update is: void Update(vector<movingEntity> chars, float time) Is this not workable? If not can someone tell me how t oget round this?

Share this post


Link to post
Share on other sites
Use a vector of pointers to movingEntity's if you want to store polymorphic types.
std::vector stores its elements in contiguous memory like an array but sizeof(movingEntity) != sizeof(Guard) so this can't work, not to mention that the types are not the same/convertible.

Share this post


Link to post
Share on other sites
What is the type of the vector where you call it, and what is the type of the vector that Update expects? The types have to be exactly the same.

But even if you get it to compile, polymorphism won't work with values. If you have vector<MovingEntity>, then that's what it contains. If you put a derived Guard in it, the Guard-specific part is simply sliced off.

You'd rather use pointers: vector<MovingEntity*>, and you can now put the address of a Guard in it, without the Guard being reduced to MovingEntity. And probably, to avoid the manual memory management that it might require, you'd use a vector<std::tr1::shared_ptr<MovingEntity> > instead.

Share this post


Link to post
Share on other sites

This topic is 2835 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this