www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Structs and Classes

reply "Mars" <- -.-> writes:
Hello everybody.
I couldn't really think of a good title for this. It's just a 
little question, about this example code:
http://pastie.org/private/4xqtze47dlx9fy9pn53sq

Apperantly I get a copy of Bar, when I call bar(), and it doesn't 
modify the actual variable of the object. But if I define Bar as 
a class, it works as expected (by silly me). Why is that? And if 
I want to use a struct for this, is the passing around of a 
pointer (like in the example) correct?

Mars
Jan 31 2012
parent Mike Parker <aldacron gmail.com> writes:
On 1/31/2012 7:45 PM, Mars wrote:
 Hello everybody.
 I couldn't really think of a good title for this. It's just a little
 question, about this example code:
 http://pastie.org/private/4xqtze47dlx9fy9pn53sq

 Apperantly I get a copy of Bar, when I call bar(), and it doesn't modify
 the actual variable of the object. But if I define Bar as a class, it
 works as expected (by silly me). Why is that? And if I want to use a
 struct for this, is the passing around of a pointer (like in the
 example) correct?

 Mars

Structs are value types, so when you return one from a function or pass as a function argument, it's actually a copy that gets handed around. Classes are reference types, so when you move those around it's very much like using a pointer. To get reference semantics on a struct, you have either use it as a pointer or use the ref keyword to create a reference.
Jan 31 2012