Overloading/Inheritance issue
Steve Schveighoffer
schveiguy at yahoo.com
Thu Aug 2 08:46:24 PDT 2007
Steve Schveighoffer Wrote:
> Regan Heath Wrote:
> >
> > Performance isn't the reason against the Java behaviour, here is Walters
> > explaination:
> >
> > <quote Walter quoting Stroustrup>
> > ...
> > </quote>
> >
> > So, as you can see it's not for performance reasons but rather to avoid
> > obscure bugs which when they manifest do so silently.
> >
> > Regan
>
Hm.. for some reason, I thought this would appear under the original thread. In any case here is the missing quote from above:
<quote Walter quoting Stroustrup>
Stroustrup gives two examples (slightly modified here):
---------------------------------
class X1 { void f(int); }
// chain of derivations X(n) : X(n-1)
class X9: X8 { void f(double); }
void g(X9 p)
{
p.f(1); // X1.f or X9.f ?
}
-----------------------------------
His argument is that one can easilly miss an overload of f() somewhere in a
complex class heirarchy, and argues that one should not need to understand
everything about a class heirarchy in order to derive from it. The other
example involves operator=(), but since D doesn't allow overloading
operator=() instead I'll rewrite it as if it were a function that needs to
alter a class state, and a derived class written later that 'caches' a
computation on the derived state:
class B
{ long x;
void set(long i) { x = i; }
void set(int i) { x = i; }
long squareIt() { return x * x; }
}
class D : B
{
long square;
void set(long i) { B.set(i); square = x * x; }
long squareIt() { return square; }
}
Now, imagine B were a complex class with a lot of stuff in it, and our
optimizing programmer missed the existence of set(int). Then, one has:
long foo(B b)
{
b.set(3);
return b.squareIt();
}
and we have an obscure bug.
</quote>
More information about the Digitalmars-d
mailing list