struct vs. class, int vs. char.
MLT
none at anon.com
Tue Apr 28 09:07:03 PDT 2009
D is really an amazing language! It really is everything that C++ did not manage to be, at least as far as my limited experience with it shows.
I noticed a couple of "problems" with it, and wanted to comment on them. It could easily be that these comments just stem from my ignorance.
1. struct vs. class
As far as I understand, these two reserved words, that in C++ mean very similar things, in D are very different. A class variable is "really" a pointer, whereas a struct is directly allocated memory.
What I don't like is that it seems that structs and classes should almost be interchangeable - one might implement something as a class and later want it to be a struct, or vice versa. It almost is actually a local decision. I might want something to be a class in one place, and a struct in another.
And, it seems that struct and class refer to several different things: (1) struct and class are allocated in different places, (2) struct is supposed to ensure its structure, and (3) struct is copied by value, whereas class by reference.
It seems to me that these are 3 different issues, and one should have control over them separately.
I find this example a bit strange:
struct S { int x;}
class C {int x;}
void main() {
{
S x ;
x.x = 1 ;
S y = x ;
y.x =2 ;
writefln(x.x) ; // x.x is 1
}
{
C x = new C ;
x.x = 1;
C y = x ;
y.x = 2 ;
writefln(x.x) ; // x.x is 2
}
}
I would have preferred to declare directly that the variable y takes or doesn't take a reference when assigned. Otherwise, it seems to me that a program that uses both (struct and class) can get mightily confusing.
Maybe the solution is to not use struct (which is I guess what is recommended unless you really need it.)
2. char[] vs. int[]
I think it is strange that
char[] x = "1234" ;
x[0] = '4' ;
Produces a run time error, but
int[] x = [1,2,3,4] ;
x[0] = 4 ;
Doesn't. I think that they both should, or both shouldn't - to be consistent (and it would be better if they both didn't). Best would be again, to allow the programmer to specify where the array (or other stuff) should be stored.
3. Builtin types vs. classes
(Here I probably am just missing the right phobos reference). D's builtin structures are very rich. Associative arrays with arbitrary keys! Given that, it is even sadder than it is in C++, that one can not inherit from the basic types. I want to implement something that is basically an associative array of one of my classes, with additional features. To do that, I will probably have to put the associative array as a component, and redefine all components/operations, or inherit from an associative array in a library...
More information about the Digitalmars-d
mailing list