D: Modules and Class Private Members

November 25, 2008

One of D’s major differences from C++ is to do with classes and their private members.

In D, any code in the same module as a class can access that class’ private members.  An example is probably useful:

    module example.Dogsarama;
    
    class Dog
    {
    public:
    
        this(int age)
        {
            m_age = age;
        }
    
        int Age()
        {
            return m_age;
        }
    
        void SetAge(int age)
        {
            m_age = age;
        }
    
    private:
    
        int m_age;
    }
    
    void SetDogAge(Dog d, int age)
    {
        // I can access this dog's privates!!!
        d.m_age = age;
    }

Because SetDogAge() is part of the same module as the Dog class, it is entitled to access and manipulate Dog’s private members.

So in another module we can do this:

    module example.Main;
    
    import std.stdio;
    import example.Dogsarama;
    
    int main(char[][] args)
    {
    	auto fido = new Dog(15);
    
    	SetDogAge(fido, 17);
    
    	writeln(fido.age());
    
    	return 0;
    }

Though I had read the main parts of the D spec I only discovered this by experimenting.  I later found the appropriate documentation which is unfortunately a bit obscure, IMO.