Constructors#

Objects can have one or more constructors. Constructors construct an object, intialise it with data or do other setup tasks.

How to use them#

The usage of a constructor is very simple:

Person p
p = Person ();

They are like a function that returns the constructed object. Often they also have parameters.

Only for classes also a new is required:

MyClass my_object = new MyClass ();

How to create them#

By default your own objects have already a constructor that does nothing. But you can also override that one with your own:

As an example we use a struct here:

struct Person {
    string name;
    int age;

    public Person () {
        this.name = "Unknown";
    }
}

A constructor looks like a method, but it doesn’t have a return type. The access modifier can be everything you want.

Inside of the constructor can be arbitrary code. You can also use the keywords this, and super ().

Tip

Classes derived from GLib.Object have a little bit different construction process. Please use the construct block there.

Multiple constructors#

The only thing to note here is that each constructor needs to have its own name:

struct Person {
    string name;
    int age;

    public Person () {
        this.name = "Unknown";
    }

    public Person.with_name (string name) {
        this.name = name;
    }
}

The constructors are differentiated by appending their identifiers to the name of the type: Person.with_name. They can be then used like this:

Person random_person = Person.with_name ("????");

Also useful#

  • Members of the object to construct can be also set just after creation this way:

    Person random_person = Person () {
        age = -10
    };