0

I am wondering if there is an easy way to save and load a decorated object in c++ as i have never done file handling in C++ before.

Currently the only object type I need to save is objects that stores values for health, damage etc. and each of these objects has at least 1 decorator. I know i could make an save function for each of the classes however I'm unsure how I would load the object.

Edit: The way that i have set up the decorator is like so. new Champion(new Monster()) where the Champion is the decorator.

  • 2
    Your question would be 10x clearer if explained exactly how you implemented the decorator pattern. There are several possible implementations, and the save/load technique probably depends on which one you chose. – Doc Brown Jan 4 '15 at 18:58
  • @DocBrown sorry i didn't realize there was more than one way – Fraser S Jan 4 '15 at 19:08
1

Writing objects of any kind to a file (whether decorators are involved or not) requires serializing those objects somehow, and loading them later requires deserializing them. Most of the time, (de)serializing objects means converting them to and from strings.

You appear to be asking how to serialize objects. For most simple objects, this is very straightforward and you can pretty much do whatever you want. For instance, you might choose to serialize a std::tuple with 0, 1 and 2 as the string "<0,1,2>". For some objects, like TCP sockets, serialization is inherently impossible, though you may be able to serialize some related information like what IP addresses they were connected to.

In principle, decorators shouldn't make this more difficult. At most they might increase the number of (de)serialization methods you need to implement. We may need more information about your objects to figure out why you're stuck.

If you're asking for common approaches to serializing more complex objects, or large collections of objects, I would suggest looking at the JSON and XML formats. There are plenty of libraries for generating and parsing them.

|improve this answer|||||
  • thanks, I take it that's its essentially saving an object the way it was created then loading the object back in? The main reason i'm stuck is that i haven't come across examples of saving and loading a decorated object. – Fraser S Jan 4 '15 at 18:24
  • If you could show us what your "decorated object" looks like exactly, I could offer more concrete advice. For instance, I'd be tempted to just use a JSON like "{object:{x:2,y:3},decorator:{d:5}}", but I have no idea if that makes sense for the type of decoration you're working with. – Ixrec Jan 4 '15 at 20:18
  • Thanks for the help i've ended up using xml files. with any luck it wont take me long to implement into my code – Fraser S Jan 4 '15 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.