According to Bjarne Stroustrup, references were introduced into C++ to support operator overloading:
References were introduced primarily to support operator overloading.
C passes every function argument by value, and where passing an object by value would be inefficient or inappropriate the user can pass a pointer. This strategy doesn't work where operator overloading is used. In that case, notational convenience is essential because users cannot be expected to insert address-of operators if the objects are large. For example:
a = b - c;
is acceptable (that is, conventional) notation, but
a = &b - &c;
is not. Anyway,
&b - &c
already has a meaning in C, and I didn't want to change that.
Having both pointers and references in the language is a constant source of confusion for C++ novices.
Couldn't Bjarne have solved this problem by introducing a special language rule that allowed object arguments to decay into pointers if a user-defined operator function exists that takes such pointers?
The declaration and usage of subtraction would then have looked like:
Foo operator-(const Foo* x, const Foo* y);
a = b - c;
Was such a solution ever proposed/considered? Would there be any serious downsides to it?
Yes I know, references provide other advantages due to their restrictions, but that's not the point.
Interestingly, the assignment operator of C with classes seems to have worked exactly like that:
Changing the meaning of assignment for objects of a class [...] is done by declaring a class member function called
operator=
. For example:class x { public: int a; class y * p; void operator = (class x *); };
operator*()
could, syntactically, return a copy. Edit: Oh, wait. I can't think ofoperator+=()
and the likes to work without (some form of) references. – sbithe direct reason I introduced them in C++ was to support operator overloading
– fredoverflowoperator=(const Foo* rhs);
which makes you wonder why Bjarne didn't stay on that road... – fredoverflowfoo + foo
copy its arguments". Instead of "why can't I have an array of references" you get "why doesoperator +(foo*, foo*)
fail when provided two pointers". – Dennis Zickefoose