Links

Categories

Tags


« | Main | »

Support for delegating constructors added

By Jewe | February 16, 2016

JewelScript 1.4 supports delegating constructors. A delegating constructor is a constructor that calls another constructor of the same class during initialization time, in order to simplify and generalize initialization of the instance.

A simple code example might make this more clear:

class Person
{
    string Name;
    string Job;
    int Age;
    
    method Person(string n, int a)
    {
        // initialize all variables here
        Name = n;
        Job = "No Job";
        Age = a;
    }

    method Person(string n, string j, int a)
        extends Person(n, a)
    {
        // all variables already initialized
        Job = j;
    }
}

JewelScript requires that all member variables are explicitly initialized in all constructors of a class. If the class is inheriting or extending, it also enforces that all base-class constructors are explicitly called from every constructor. With classes that have multiple constructors, this can become some serious typing effort.

Delegating constructors save us this typing effort. We only have to fully initialize the instance in one constructor, and then call that constructor from all the others.

Which constructor delegates to which is open to choice, and probably a matter of personal taste. Though turning the example around will yield slightly more efficient code:

class Person
{
    string Name;
    string Job;
    int Age;
    
    method Person(string n, string j, int a)
    {
        // initialize all variables here
        Name = n;
        Job = j;
        Age = a;
    }

    method Person(string n, int a)
        extends Person(n, "No Job", a)
    {
        // all variables already initialized
    }
}

Topics: code examples, docs, news | Comments Off on Support for delegating constructors added

Comments are closed.