struct vs. class, int vs. char.

Jarrett Billingsley jarrett.billingsley at gmail.com
Tue Apr 28 10:28:24 PDT 2009


On Tue, Apr 28, 2009 at 12:07 PM, MLT <none at anon.com> wrote:

> 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.

I hear this all the time from C++ users.  But in practice, it
virtually never comes up.  I have never, in my five years of using D,
wanted to change a class to a struct or vice versa, or ever seen
anyone else doing that (or complaining about its difficulty).  The
only people who complain are those who don't use the language ;)

> 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.

Again, in practice, you will virtually always want *either* value
semantics *or* polymorphism.  In the few cases where you need both,
you can imitate it with mixins and the like (and with D2, 'alias this'
is nice).

> 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.

Again, in practice, it doesn't :)  You always use some types as values
and others always as references.  Are C programs that use both ints
and char* s mighty confusing?

> Maybe the solution is to not use struct (which is I guess what is recommended unless you really need it.)

Please don't make everything a class.  This isn't Java ;) What is
instead recommended is that you use structs for value types and
classes for everything else.



More information about the Digitalmars-d mailing list