tags:

views:

74

answers:

2

Will be nice if I got 'nested members' in D language, so I have the inglorious idea to code


class Keyboard
{
    struct  Unused {
        string key1 = "Wake Up";
        string key2 = "Sleep";
        string key3 = "Power";
    }

    Unused unused;
}

int main()
{
    Keyboard kb;
    kb.unused.key1 = "Scroll Lock";

    return 0;
}

Okay, it's a bad example that segfault too. But I'm learning object-oriented programming and don't know if it's a good thing to do, or how to do.

+3  A: 

There's nothing wrong with doing that per se, the problem here is that kb is still null. You need to create a Keyboard object:

Keyboard kb = new Keyboard();

If you don't want to type Keyboard twice, you can use auto:

auto kb = new Keyboard();

And D will automatically determine the correct type for you.

It's fairly common practice to group related objects together like that into a struct, although usually you'll want a more descriptive name than Unused (otherwise, why have the namespace?).

Peter Alexander
It's a shame! Has some difference on running program from auto to Keyboard, or is the same thing once compiled?
Pedro Lacerda
It's exactly the same: the compiler can see that `new Keyboard()` returns a `Keyboard` at compile time and just adds the type itself. There is no difference in the compiled code.
Peter Alexander
@pslacerda, it is called type inference and used everywhere in D. foreach(w; words), sort(words); Even sort here has inference. The full length tho call it would be sort!(immutable(char)[][], "a < b")(words)
he_the_great
+2  A: 

You can use the syntax you first suggested. Just make unused a static member. This works fine:

class Keyboard
{
    struct Unused {
         string key1 = "Wake Up";
         string key2 = "Sleep";
         string key3 = "Power";
    }

    static Unused unused;   // **This is now a static member**
}

int main()
{
    Keyboard kb;
    kb.unused.key1 = "Scroll Lock";

    return 0;
}
Justin W
Isn't the case...
Pedro Lacerda