Re: References and pointers
On Dec 31, 1:31 pm, Simon Saize <bl...@nospam.invalid> wrote:
Hi -
What's the point of having references (&)? Why don't we just use
pointers (*)?
Thanks.
Because references can do things pointers can't in C++ (the reverse is
true as well).
C++ references benefits includes declaring and implementing operators.
They also support polymorphic calls, just like pointers do.
References make the code's intentions clear and unambiguous.
(doesn't mean C++ is better, in some respects it does mean its safer)
References can offer guarentees that pointers can't.
For example:
void foo(const int& r)
{
// do stuff
}
guarentees that reference r, if accessed within that function body,
will refer to the original integer.
That relationship is indestructeable.
On the other hand, since a pointer_to_const is reseatable:
void foo(const int* p)
{
int x(88);
p = &x; // oops
// do stuff
}
and a const pointer_to_const can be const_cast away:
void foo(const int* const p)
{
int x(88);
int* p_ = const_cast<int*>(p);
p_ = &x; // oops
// do stuff
}
a pointer of any flavour is unable to offer the same guarentee a
reference can.
void foo(const int& r) clearly states the intentions of the code.
There is no uncertainty.