Topic: Overloaded return types (was expression
Author: shepherd@debussy.sbi.com (Marc Shepherd)
Date: Thu, 21 Apr 1994 12:04:48 GMT Raw View
In article 95s@biles.com, daniels@biles.com (Brad Daniels) writes:
> The ARM discusses in section 13 (.0) how functions differing only in return
> type cannot be overloaded. It gives the example:
>
> X operator+(const X&, const Y&);
> Y operator+(const X&, const Y&);
>
> void f(X a, Y b)
> {
> X r1 = a+b;
> Y r2 = a+b;
> }
>
> Then talks about how it is difficult for a computer or human to determine
> which call is really meant.
Here's an analogy. The code:
double d = 4/3; // d = 1.0, not 1.3333333333...
consists of two operations. First, 4 is divided by 3; second, the result is
used to initialize d. The operation 4/3 is done using integer arithmetic,
because both of its operands are integers. The compiler does not analyze the
full expression to decide what kind of operation to perform.
Likewise, in:
X r1 = a+b;
the compiler analyzes a+b all by itself, without regard to the full expression.
This may seem silly, but imagine the ambiguity that would result if compilers
were required to fully analyze expressions like this:
X r1 = (a+b+c+d)*z/2;
before deciding which operations to use. If you think the current overloading
rules are complex, imagine what they would be if all the operations in the above
expression were overloaded on the return type!
> . . . How does this case differ from:
>
> class B;
> class C;
>
> class A {
> public:
> A();
> operator B();
> operator C();
> };
>
> class B {
> public:
> B();
> };
>
> class C {
> public:
> C();
> };
>
> void f(A &a)
> {
> B b = a;
> C c = a;
> }
>
The expression
B b = a;
contains just one operation--initializing b with a. The compiler analyzes the
types of b and a, and finds that they are different. Then, it finds a conversion
that can turn a into a B. No sweat.
This is analagous to:
double d = 1;
Here, the compiler sees that d is a double, but 1 is an int. It converts 1 to
double and then completes the initialization.
---
Marc Shepherd
Salomon Brothers Inc
mshepherd@mhfl The opinions I express are no one's but mine!