Post-ctor ctor

Andrej Mitrovic andrej.mitrovich at gmail.com
Sun Aug 7 11:16:23 PDT 2011


Just throwing an idea..

structs are great since you don't have to make a special constructor
just to initialize its fields. E.g.:

struct Foo
{
    int a;
    int b;
    int c;
    int d;
}

void main()
{
    auto foo = Foo(1, 2, 3, 4);
}

But what if I add an extra couple of fields that have to be
initialized based on only the first 4 fields, and I still want to keep
the same call in the user code? Here's a hypothetical case:

struct Foo
{
    int a;
    int b;
    int c;
    int d;

    int sum;
    int average;

    post this()  // post-ctor ctor
    {
        sum = a + b + c + d;
        average = (a + b + c + d) / 4;
    }
}

void main()
{
    auto foo = Foo(1, 2, 3, 4);
}

A post-construction ctor would do any final initializations after
field initialization, or after a call to a custom ctor. Otherwise I
would have to write:

struct Foo
{
    int a;
    int b;
    int c;
    int d;

    int sum;
    int average;

    this(int a, int b, int c, int d)
    {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
        postCtor();
    }

    private void postCtor()
    {
        sum = a + b + c + d;
        average = (a + b + c + d) / 4;
    }
}

void main()
{
    auto foo = Foo(1, 2, 3, 4);
}

I see that as needlessly implementing in user-code what the compiler
can already do on its own. If we had a post-ctor ctor, partial
initialization could be done via field initialization instead of using
a hand-written ctor, and then a post-ctor would initialize the rest of
the fields.

Good idea / bad idea?

I have a feeling this would clash with that "can't have a default ctor
on a struct" rule. I just hate having to manually write ctors for
cases where the first N fields are initialized in order while the rest
need special initialization.


More information about the Digitalmars-d mailing list