private vs protected in Interfaces

Andrej Mitrovic andrej.mitrovich at gmail.com
Fri Aug 13 15:35:30 PDT 2010


More code from TDPL:

import std.exception;

interface Transmogrifier
{
    final void thereAndBack() {}
    
    private:
        void transmogrify();
        void untransmogrify();
}

class CardboardBox : Transmogrifier
{
    private:
        override void transmogrify() { }
        override void untramsogrify() { }
}

class FlippableCardboardBox : CardboardBox
{
    private:
        bool flipped;
        override void transmogrify()
        {
            enforce(!flipped, "Can't transmogrify: box is in time machine mode");
            super.transmogrify();   // should be an error, cannot invoke private
                                    // method CardboardBox.transmogrify
        }
        override void untransmogrify()
        {
        }
}

import std.stdio;

void main()
{
    auto obj = new FlippableCardboardBox;
    obj.transmogrify();
}

TPDL, page 216: "Making an overridable function private in an interface..prevents an implementation from calling the super function".

But the code example above compiles and runs fine.

On the next page: "A simpler solution is to relax access of the two overridables in Transmogrifier from private to protected:"

interface Transmogrifier
{
    final void thereAndBack() {}
    
    protected:
        void transmogrify();
        void untransmogrify();
}

This will not work. I get back:
test.d(13): Error: class test.CardboardBox interface function Transmogrifier.transmogrify isn't implemented
test.d(13): Error: class test.CardboardBox interface function Transmogrifier.untransmogrify isn't implemented
test.d(20): Error: class test.FlippableCardboardBox interface function Transmogrifier.transmogrify isn't implemented
test.d(20): Error: class test.FlippableCardboardBox interface function Transmogrifier.untransmogrify isn't implemented
test.d(20): Error: class test.FlippableCardboardBox interface function Transmogrifier.transmogrify isn't implemented
test.d(20): Error: class test.FlippableCardboardBox interface function Transmogrifier.untransmogrify isn't implemented

Which doesn't make any sense, the derived classes have the functions implemented. 

Btw Andrei, you threw that enforce in without any explanation (I don't think I saw it in any earlier examples), and you're missing an import (but I've put that in the errata).


More information about the Digitalmars-d mailing list