Saturday, 9 April 2016

Paper and Bag

Last time I was talking about the difficulty of inheriting classes, but after all it was not that hard. Classes Paper and Bag were derived from Item class. Paper contains scroll functionality and Bag is a container item. Both these were previously in Item class, but for most items they were empty data. Moving that data and functionality to derived classes not only makes source code better (less chances for bugs), but saves both memory and save game space.

As I said deriving itself is actually quite easy, because container functionality was already in base class as virtual functions so they work automagically. The problem is in the way items are created and stored in lists. Since C++ doesn't as default support heterogeneous lists you can only put class instances of one type in a list. However this is not such a big problem than I thought, because in this case you can put all items in Item type list and when you need special functionality of Paper or Bag you simply cast Item to Paper or Bag, depending on the object type. It's kind of ugly, but in a way typical C++ solution.

The only real problem is something called object slicing, but it doesn't happen with list of pointers to instances.

Last thing is when you load object data you need to know what the object type is when using heterogeneous lists of objects. I've solved this in theory by using a trick to peek the saved object type (from loaded chunk of data that contains the entire list) before creating the object, since obviously you can't create the object until you know if it's a regular Item, Paper or Bag.

No comments:

Post a Comment