Search code examples
doop

Namespaces with classes and structs?


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.


Solution

  • 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?).