Can I preserve the values in a parent class when I overwrite it with a child class?

Hello,
my current problem is that I’ve got a class FieldInfo which has a child class called Building.

Now I generate FieldInfos for every field of my map during map generation. I store those FieldInfos in a 3d array FieldInfos[,,]. When I want to build a building I can stick the child class into the parent array. fieldInfos[x,y,z] = new Building(Construction.House);My problem here is that this would overwrite the values in fieldInfos (which are kind of important since they contain gameplay relevant map data) with the standard constructor of FieldInfos if I understand it correctly.

Is there some way to maintain the properties of the old FieldInfo object when I overwrite it with a Building object? Or would it make more sense to just make another array for the Building class and don’t have it inherit from the FieldInfo class?

All you really need to do is pass the values to be preserved in the original FieldInfos to the constructor of the Building so it copies those values into its base. There’s no way to ‘preserve’ the original FieldInfos, the Building is a separate instantiation, it can’t slice the derived part onto an existing instantiation of the base.


That said, the question that comes to my mind is a mystery from my viewpoint, since I don’t get any information about your design - but is a Building a FieldInfo? More to the point, not just from the standpoint of data, but from the standpoint of member functions, does a Building need any of the member functions of the FieldInfo base in order to function correctly as a Building?


If the answer reveals that a Building is otherwise so separate from the methods and data of FieldInfo that you’re merely tacking the Building onto a FieldInfo because that base has pertinent bits of data but is otherwise not a functional base component, then perhaps the relationship isn’t inheritance, but one of ownership. Perhaps a Building should be something that attaches to an existing FieldInfo, and can use the FieldInfo through an interface that communicates between them.


From this distance I have no information that informs me which is the truth in your case, but such is the nature of object design where the basic question is to differentiate between things that “are a” (or “is a”) and those things that “have a” class. If shape is a base, then obviously circles, squares and triangles ARE shapes. That satisfies the “is-a” relationship, and indicates the circle, square and triangle may well derive from the shape base. However, consider the relationships established in Unity itself (they are well chosen) where components are added to a GameObject because they are “owned” not “comprised of” the attached classes. Derivation is an intimate relationship, whereas ownership is causal and requires a protocol for interaction (and that limitation is functional, lending a design a more solid foundation).