I don’t know how to explain this properly, someone please edit my title and post as needed. I thought this could be solved with polymorphism, but I couldn’t get it to work. What I would like to have is as following.
I’m going to have different shapes and they all have different variables. For example, to describe a particular shape A I need:
Mandatory fields for every shape:
-
starting and ending point (composed
of 3 double variables: x, y and z) -
name (string)
A shape may or not need the following fields (maybe in the future I will need more)
- Length, width, height (all double)
- Angle
- Other variables which could be double or string
The thing is, this needs to flexible, as every shape is going to be described using XML, which I then need to load into the program. For example a cube would work like this:
<?xml version="1.0" encoding="utf-8" ?>
<structure name="Cube">
<variables>
<point name="start" />
<point name="end" />
<length name="width" min="1" max="10000" unit="mm" />
<length name="height" min="1" max="10000" unit="mm" />
</variables>
<points>
<point name="topLeft">
<x>start.x</x>
<y>start.y - height/2</y>
<z>start.z</z>
</point>
<point name="topRight">
<x>end.x</x>
<y>end.y - height/2</y>
<z>end.z</z>
</point>
<point name="bottomLeft">
<x>start.x</x>
<y>start.y + height/2</y>
<z>start.z</z>
</point>
<point name="bottomRight">
<x>end.x</x>
<y>end.y + height/2</y>
<z>end.z</z>
</point>
</points>
<connections>
<connection type="line">
<point name="topLeft" />
<point name="topRight" />
<point name="bottomRight" />
<point name="bottomLeft" />
<point name="topLeft" />
</connection>
</connections>
</structure>
So what I thought is, I have a base class called CVariable (with 2 abstract methods, parseString and toString), which I then inherit to make CLength (new attribute double length), CPoint (new attribute double x, y and z) and CName (new attribute string name). I can then have a class called CShape which has a list of CVariable, CPoint and CName (the connections, just a name identifying the point to be connected). The problem is, I believe, if I have a list of CVariable, I can’t access the new attributes. Am I right?
Sorry if it’s not clear, I will edit to add any information needed. Thanks a lot in advance.
The scheme you’re thinking in is usually called a “variant”.
CVariableis not a good name for this, it’s just to unspecific. But you’re thinking in the right direction already. By deriving from a common base class you can pack the elements in a common container. The trick to access those derived types is using the runtime type information system: There is thetypeofkeyword telling you the actual type of the object you’re referring to: http://msdn.microsoft.com/de-de/library/58918ffs.aspxA word of warning: Getting into a situation where one needs a variant is often a hint, that something in the design of the data structure may be flawed and rethinking the problem is a good idea.