Changing the class data underneath some reference
David Colson
david at peripherallabs.com
Thu Nov 30 00:46:33 UTC 2017
On Thursday, 30 November 2017 at 00:40:51 UTC, David Colson wrote:
> Hello all!
>
> I'm getting settled into D and I came into a problem. A code
> sample shows it best:
>
> class SomeType
> {
> string text;
> this(string input) {text = input;}
> }
>
>
> void main()
> {
> SomeType foo = new SomeType("Hello");
>
> SomeType bar = foo;
>
> foo = new SomeType("World");
>
> writeln(bar.text); // Prints hello
> // I'd like it to print World
> }
>
> In the C++ world I could do this using pointers and changing
> the data underneath a given pointer, but I can't use pointers
> in D, so I'm not sure how I can get this behaviour?
>
> I'd be open to other ways of achieving the same affect in D,
> using more D like methods.
I made an example demonstrating what I'd do in C++:
class SomeType
{
public:
std::string text;
SomeType(std::string input) {text = input;}
};
int main()
{
SomeType foo = SomeType("Hello");
SomeType* bar = &foo;
foo = SomeType("World");
std::cout << bar->text << "\n"; // Prints World
}
More information about the Digitalmars-d-learn
mailing list