Note: This website is archived. For up-to-date information about D projects and development, please visit


Part of TutorialFundamentals


A class is a similiar idea to a struct, but allows more abstract designs.


import std.stdio;

class Foo
    /* #1 */
    int number;
    string name;
    /* #2 */
    this(int number, string aname)
        /* #3 */
        this.number = number;
        name = aname;
    void printMe()
        /* #4 */
        string name = "I'm hiding access to!";
        writefln("number: %s, name: %s, internal name: %s", number,, name);

class Bar
    int x;
    int y;
    /* #5 */
        x = 5;
        y = 6;
    void printMe()
        writefln("x: %s, y: %s", x, y);

void main() 
    /* #6 */
    Foo foo = new Foo(4, "hello");
    /* #7 */
    foo.number = 1; = "world!";
    /* #8 */
    Bar bar = new Bar;


1: A class can have it's own variables.

2: A class can have a user-defined constructor called this(). It gets called when we create an instance of the class. A constructor can optionally parameters.

3: If the parameter in a method of a class has the same name as a variable in the same class, you can use this to explicitly refer to the class instance, and use the dot-notation to access its variables. This is what we do when we use the first parameter to assign to our variable, while the second paremeter doesn't conflict with any names so we don't have to use this in this case.

4: A class can have its own methods. Again, you don't necessarily have to use this to refer to the class variables, unless there are any paramters or variables defined inside the method that have conflicting names with the class variables. Note how string name is hiding access to name of the Foo instance, but we can use this to work around this issue.

5: We can make a constructor that doesn't take any arguments. We could also provide multiple constructors, but that's not shown here.

6. A class instance is made by using the new keyword, following by a call to the constructor. The constructor is called by using the class name ( Foo ), followed by arguments in parantheses if a constructor requires any. We can then call the methods of the class instance.

7. Foo's variables are public by default. This means that you can read and modify them directly by using dot-notation. In some cases, this is desirable. But most often you would protect the variables from being easily modified outside the class by using access specifiers (More info on this is in the docs).

8. Since Bar's constructor doesn't take any arguments, we don't need to add the parantheses when calling its constructor.

Note: In D1 code (and some D2 code), you might notice the use of the delete expression with class instances. The delete expression is scheduled for deprecation, and you should not use it with new code.

More Information

See the D Specification.