Copying and Assignment

Get to learn about copying and assignment of class objects.

We'll cover the following

Copying

Copying affects only the variables, not the object.

Because classes are reference types, defining a new class variable as a copy of another makes two variables that provide access to the same object. The actual object is not copied.

Since no object gets copied, the postblit function this(this) is not available for classes.

auto variable2 = variable1;

In the code above, variable2 is being initialized by variable1 and the two variables start providing access to the same object.

When the actual object needs to be copied, the class must have a member function for that purpose. To be compatible with arrays, this function may be named dup(). This function must create and return a new class object. Let’s see this on a class that has various types of members:

class Foo {
    S      o;  // assume S is a struct type
    char[] s;
    int    i;

// ...

    this(S o, const char[] s, int i) { 
        this.o = o;
        this.s = s.dup; 
        this.i = i;
    }
    Foo dup() const {
        return new Foo(o, s, i); 
    }
}

The dup() member function makes a new object by taking advantage of the constructor of Foo and returns the new object. Note that the constructor copies the s member explicitly using the .dup property of arrays. Being value types, o and i are copied automatically.

The following code makes use of dup() to create a new object:

Get hands-on with 1200+ tech skills courses.