what was wrong with struct & class in C++?

Yigal Chripun yigal100 at gmail.com
Wed Dec 12 17:51:13 PST 2007


 > a question: should matrices be structs or classes?

I'd like to clarify your question:
do you want to ask -
a) whether they should be value types or reference types?
or
b) whether they should be implemented with D structs or D classes?

if you mean a than it really doesn't matter.
you are quite right that you can implement OOP features with both 
reference and value semantics. doing both is redundant because they 
achieve the same goal.
i.e. passing by value achieves the same as const reference and passing 
the address of the value achieves the same as passing by mutable reference.
so it's just a question of implementation and most languages choose 
reference semantics due to the more efficient memory use.
so in this case the consensus is the better option.

also note that you can mix-n-match: you can implement one semantic with 
the other:
ref to value: you can have a dup method (clone in java, but you knew 
that already) although it should be avoided and probably isn't needed in 
the general case.
value to ref: you can pass addresses of values to simulate references.

if you meant b than i think that classes should be used.
I'm new to D, but from what little i know, if you want OOP behavior (and 
matrices would benefit from polymorphism) than you need to use a class 
and not a struct.

the semantics shouldn't matter as it's a matter of implementation and 
not interface. (ideally you'd just use "in" and "inout" and let the 
compiler optimize when you pass around parameters).
if you want a matrix to be a value type you can simulate that with a dup 
method, i think.
D structs should only be used for PODs. a good example would be a struct 
containing an internet address where you need it to be in a specific 
memory layout (endian-ness).

also, if you care about heap allocation vs. stack, than you could always 
use scope classes which would be stack based.

that's all from a theoretical POV of course, practically, there maybe 
other issues that influence that decision. also const still has a few 
kinks that need to be sorted out in D.

Just my 2 cents..





More information about the Digitalmars-d mailing list