struct vs class

spir denis.spir at gmail.com
Sun Nov 14 03:08:49 PST 2010


Hello,


There seems to be 2 main differences between structs & classes:
1. structs instances are direct values, implement value semantics; while class instances are referenced (actually "pointed")
2. classes can be subtyped/subclassed in a simple way; structs cannot be really subtyped -- but there is the "alias this" hack

I am trying to understand what should be the rationale behind choosing one or the other form of structured type. Letting aside subtyping considerations, meaning concentrating on the consequences of the first point above. Here are my views on the topic:

* On the semantic side:
An element should be referenced when its meaning is of a "thing", an entity that has an identity distinct from its value; a things remains "itself" whatever its evolution in time; it can also be multiply referenced. For instance, a visual form that can change would be a thing.
An element should be a value type when it provides information about a thing; a value makes no sense by itself, it is bound to what it describes an aspect of; referencing a value is meaningless, only copy makes no sense. For instance, the position & color of a visual form should be values.

* On the efficiency side:
Struct instances have fast creation, because allocated on the stack (*)? Class instances are costly to create. But then, passing class instances around is light, since only a reference is copied, while struct instances are copied at the field level.
Both of these points may conflict with semantic considerations above: we may want to use structs for fast creation, but if ever they mean "things", we must think at referencing them manually and/or using ref parameters. We may want to use classes for light passing, but if they mean values, we must either never assign them or manually copy their content. It's playing with fire: very dangerous risks of semantic breaks in both cases...


Here is an example: a module implementating general-purpose tree/node structure.
Let us say there are both a Tree & Node types -- the nodes do not implement global methods, only the tree does. So, a node just holds an element and a set of child nodes, possibly methods to manipulate these fields. A tree in addition has methods to traverse nodes, search, insert/remove, whatever...
What kinds should be Node & Tree? Why? Are there sensible alternatives? If yes, what are the advantages and drawback of each? In what cases?
(questions, questions, questions...)


Denis

(*) Is this true? And why is the stack more efficient than the heap?

-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d-learn mailing list