copying objects

lets say i have a custom class called DOODAD and i have a list of doodads stored in a map like this.
std::map <std::string, DOODAD*> doodads;

each doodad stored is unique in its variables. one doodad may be a piece of wall in the game and is basically set up so the game will know you cant see or walk thru it. while another may be a door a that will have an interactive code that allows it to open and close that changes its properties dynamically.


now say i have a piece of code somewhere else that wants to basically copy one of the stored doodads. It cannot just use the stored doodad, because if its a door it will need to changes its variables dynamically and then i would have every door in the game open and close at the same time.

would this be done like say

DOODAD* doodoo = new DOODAD(DoodadManager::doodads["door"]&);
by dereferencing the pointer stored in doodads would it copy the object?

is there a better way of doing this all together?
DOODAD* doodoo = new DOODAD(*DoodadManager::doodads["door"]) ;

I don't see the utility of having a bunch of default objects around just so you can copy them. These objects don't know how to default-construct themselves? Is it really an instance of a DOODAD you want here or an instance of a derived type?


The DoodadManager builds all the standard DOODADs when the game launches. they are built dynamically by loading data from text files. i assumed it would be more resource friendly to have all these prebuilt and just copy them, rather than having to load and build one everytime i needed one.

knowing this can i still use a derived type? if so then how, as i'm not familiar with using these.
IIRC you've created some prototypes, and store them in a correspondence.
You want to use this prototypes to create other objects. But you can't make the prototype classes, because the properties are loaded at runtime from a file.
Also you used pointers because you are storing derived types.

knight Joan_of_Arc = *dynamic_cast<knight*> (Manager::correspondence["knigth"]);
Note that Joan_of_Arc is not a pointer.

If you do need pointers (I can't come up with a reason)
knight *Joan_of_Arc = Manager::correspondence["knigth"]->clone();
1
2
3
4
5
6
7
8
9
10
class DOODAD{
public:
  virtual DOODAD* clone() = 0;
};
class knight: public DOODAD{
public:
  virtual knight* clone(){
    return new knight(*this);
  }
};


A good reading http://en.wikipedia.org/wiki/Design_Patterns (you may be especialy interested in Creational Patterns)
Last edited on
Topic archived. No new replies allowed.