The impoliteness of overriding methods

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Dec 19 23:41:37 PST 2012


On Thu, Dec 20, 2012 at 08:26:18AM +0100, Jacob Carlborg wrote:
> On 2012-12-20 01:06, H. S. Teoh wrote:
> >On Thu, Dec 20, 2012 at 12:11:34AM +0100, Andrej Mitrovic wrote:
> >>Some interesting blog post:
> >>http://journal.stuffwithstuff.com/2012/12/19/the-impoliteness-of-overriding-methods/
[...]
> >Interestingly enough, in the "polite" overriding case, the call to
> >inner is undefined until it's defined in the derived class. Which
> >means that a method that calls inner is a kind of pseudo-abstract
> >method (since abstract methods are those that *must* be implemented
> >by the derived class). So if we were to implement this in D, we could
> >extend the meaning of 'abstract':
> >
> >	class Base {
> >		// The current, usual overridable method
> >		void replaceMe() {
> >			writeln("A");
> >		}
> >
> >		// Abstract, because chain(chainMe) is undefined until
> >		// the derived class implements it.
> >		abstract void chainMe() {
> >			writeln("B");
> >			inner.chainMe(); // call derived class method
> >					// 'inner' is a tentative
> >					// keyword
> >			writeln("C");
> >		}
> >	}
> >
> >	class Derived : Base {
> >		override replaceMe() {
> >			writeln("D");
> >			Base.replaceMe();
> >			writeln("E");
> >		}
> >
> >		// Base.chainMe is abstract, so we have to implement
> >		// this method.
> >		override void chainMe() {
> >			writeln("F");
> >		}
> >	}
> >
> >	void main() {
> >		auto d = new Derived();
> >		d.replaceMe();	// prints D A E
> >		d.chainMe();	// prints B F C
> >	}
> >
> >
> >T
> >
> 
> What's the difference compared to calling "super".
[...]

The difference is that you can do things like this:

	class Base {
		abstract void chainMe() {
			if (condition) {
				chainMe();	// recursion
			} else {
				inner.chainMe();
			}
		}
	}

Which cannot be easily reproduced using .super.


T

-- 
Ruby is essentially Perl minus Wall.


More information about the Digitalmars-d mailing list