• Advertisement
Sign in to follow this  

Making copies of virtual objects

This topic is 3640 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

Hey all, I have a 'Mission' class, and a number of specific missions that extend from this base class. For example: class Mission { public: int missionLevel, cashReward; bool completed, failed; Mission(); virtual void Update() {cout << "base" << endl;} }; class Cop1 : public Mission { public: int arrestsRequired; Cop1(); void Update() {cout << "mission1" << endl;} }; etc.. I then have a Mission Manager object, which holds a vector of pointers to these missions. When a player selects a new mission, I want them to make their own copy of one of these missions, and update it as they kill/arrest people, etc. The problem I'm having is that when I make a copy of one of these missions, only a copy of the base class is made, not the specific mission. For example: Cop1 mission1; std::vector<Mission*> copMissions; copMissions.push_back(&mission1); Mission tempMission = *copMissions[0]; tempMission.Update(); //OUTPUTS: "base" I would hope that this would output "mission1", but it doesn't.. it outputs "base". I think I know why this is happening.. because I'm casting tempMission as Mission... However, if I do this: Cop1 mission1; std::vector<Mission*> copMissions; copMissions.push_back(&mission1); Mission* tempMission = copMissions[0]; tempMission->Update(); //OUTPUTS: "mission1" It correctly outputs "mission1".. but this time it doesn't make a copy of the mission.. but rather is alterting the original mission.. which I don't want. Basically I have to combine the two.. maybe I can use the heap? But I don't know how to create the right type.. I'd like to do something like: Mission* tempMission = new copMissions[0]; that doesn't work, obviously.. but hopefully it shows what I'm trying to achieve. Any ideas? Thanks.

Share this post


Link to post
Share on other sites
Advertisement
The effect you are seeing is called slicing to overcome this coders tend to use a virtual function (general standard is to call this clone). See parashift for an example of cloning.

edit - fixed link

Share this post


Link to post
Share on other sites
Quote:
Original post by the_edd
I made a smart-pointer to handle this for you.

value_ptr<>

Actually Edd your site was one of the hits I got when looking for an example of using a clone method :)


Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement