473,387 Members | 1,549 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Why is there a need for reference in C++?

Hi,
I have been using C++ for a while. I am not entirely clear with
the concepts of reference in C++.

- Why was there a need for introducing a concept called "Reference" in
C++ when everything was working fine with normal pointers?

- Is there anything that a reference can do that a pointer cannot ???

Please clarify,
Sarathy

Jul 29 '06 #1
11 1496
On 29 Jul 2006 11:39:53 -0700, "sarathy" <sp*********@gmail.com>
wrote:
>Hi,
I have been using C++ for a while. I am not entirely clear with
the concepts of reference in C++.

- Why was there a need for introducing a concept called "Reference" in
C++ when everything was working fine with normal pointers?

- Is there anything that a reference can do that a pointer cannot ???

Please clarify,
Sarathy
Pointers cause excess friction, and are believed to have been the
cause of explosions in space craft. References were invented for safe
use aboard spacebound vehicles.
Jul 29 '06 #2
sarathy wrote:
Hi,
I have been using C++ for a while. I am not entirely clear with
the concepts of reference in C++.

- Why was there a need for introducing a concept called "Reference" in
C++ when everything was working fine with normal pointers?
It wasn't fine, was it? Pointers *are* tricky. Now, in C++ the trickyness of
pointers is compounded by exceptions: since exceptions can divert the flow
of control at almost any point and toward unknown locations, the basic
requirement of a pointer that every new() is matched by a delete() along
each path of execution is harder to match. Thus, a device was created to
eliminate some uses of pointers. References and standard containers are in
this category. Other devices, like auto_ptr, were introduced to mitigate
the dangers for the remaining cases of pointer use.

- Is there anything that a reference can do that a pointer cannot ???
References can extend the life-time of temporaries:

#include <iostream>

struct log {

log ( void ) {
std::cout << "construction" << std::endl;
}

log ( log const & ) {
std::cout << "copy" << std::endl;
}

~log ( void ) {
std::cout << "destruction" << std::endl;
}

void access ( void ) const {
std::cout << "access" << std::endl;
}

};

log create_tmp ( void ) {
return ( log() );
}

int main ( void ) {
{
log const & ref = create_tmp();
ref.access();
}
std::cout << std::endl;
{
// warning: UB
log const * ptr = &create_tmp();
ptr->access();
}
}

// end of file
Best

Kai-Uwe Bux
Jul 29 '06 #3
In article <11**********************@75g2000cwc.googlegroups. com>,
"sarathy" <sp*********@gmail.comwrote:
Hi,
I have been using C++ for a while. I am not entirely clear with
the concepts of reference in C++.

- Why was there a need for introducing a concept called "Reference" in
C++ when everything was working fine with normal pointers?
I read "The Design and Evolution of C++" by Bjarne Stroustrup a long
time ago so I may not remember this correctly, however as I remember it
references were put in the language to make operator overload work right.
- Is there anything that a reference can do that a pointer cannot ???
class MyClass { };

MyClass operator+( const MyClass& lhs, const MyClass& rhs );

Without references, your only choices are to pass by value (which could
be quite expensive for objects of a big class, or pass by pointer which
would make the calling code look like:

MyClass a, b;
MyClass c = &a + &b;

Which seems rather clumsy.
Jul 29 '06 #4
sarathy wrote:
I have been using C++ for a while. I am not entirely clear with
the concepts of reference in C++.

- Why was there a need for introducing a concept called "Reference" in
C++ when everything was working fine with normal pointers?
Normal pointers have too many abilities, so they are high risk. We need a
feature with fewer abilities, so it's safer.
- Is there anything that a reference can do that a pointer cannot ???
It can refer to a temporary object.

It can create a syntax error when you abuse it in ways a pointer would
accept.

Think of a reference as another name for a target - an alias for a target.
Don't think of it as a different kind of pointer.

And, the next time you program a "handle" of some kind, if you don't need it
to be NULL, and don't need to index or increment it, use a reference. Put
another way, always use a reference unless you need a pointers' extra
features.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
Jul 29 '06 #5
On Sat, 29 Jul 2006 20:07:19 GMT, "Daniel T." <da******@earthlink.net>
wrote:
>I read "The Design and Evolution of C++" by Bjarne Stroustrup a long
time ago so I may not remember this correctly, however as I remember it
references were put in the language to make operator overload work right.
Interesting. And I thought they were introduced to make C++
programming more convenient and safer. "The Design and Evolution of
C++" really should be my next (and probably last) C++ book.

Best regards,
Roland Pibinger
Jul 29 '06 #6
In article <44**************@news.utanet.at>, rp*****@yahoo.com
says...

[ ... references ]
Interesting. And I thought they were introduced to make C++
programming more convenient and safer. "The Design and Evolution of
C++" really should be my next (and probably last) C++ book.
Yup, his memory was dead on in this case. D&E, 3.7, says: "References
were introduced primarily to support operator overloading."

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 29 '06 #7

Phlip wrote:
sarathy wrote:
I have been using C++ for a while. I am not entirely clear with
the concepts of reference in C++.

- Why was there a need for introducing a concept called "Reference" in
C++ when everything was working fine with normal pointers?
By accepting a Foo& instead of Foo*, it's a nice way to get polymorphic
access to objects without having to constantly test for NULL.

Jul 30 '06 #8
Kai-Uwe Bux wrote:
sarathy wrote:
>Hi,
I have been using C++ for a while. I am not entirely clear with
the concepts of reference in C++.

- Why was there a need for introducing a concept called "Reference" in
C++ when everything was working fine with normal pointers?

It wasn't fine, was it? Pointers *are* tricky. Now, in C++ the trickyness of
pointers is compounded by exceptions: since exceptions can divert the flow
of control at almost any point and toward unknown locations, the basic
requirement of a pointer that every new() is matched by a delete() along
each path of execution is harder to match. Thus, a device was created to
eliminate some uses of pointers. References and standard containers are in
this category. Other devices, like auto_ptr, were introduced to mitigate
the dangers for the remaining cases of pointer use.

>- Is there anything that a reference can do that a pointer cannot ???

References can extend the life-time of temporaries:
But what is the difference between :
[...]
{
log const & ref = create_tmp();
ref.access();
}
[...]

and :

[...]
{
log val = create_tmp();
val.access();
}
[...]

Besides the fact in the first case you won't be able to modify the
reference ?

Pierre
Jul 30 '06 #9
* Pierre Barbier de Reuille:
Kai-Uwe Bux wrote:
>References can extend the life-time of temporaries:

But what is the difference between :

[...]
{
log const & ref = create_tmp();
ref.access();
}
[...]

and :

[...]
{
log val = create_tmp();
val.access();
}
[...]

Besides the fact in the first case you won't be able to modify the
reference ?
As Kai-Uwe wrote, the reference extends the lifetime of the temporary.
Here the type of the temporary can be a class derived from 'log'. The
non-reference copies the temporary to a variable of type 'log', possibly
slicing.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 30 '06 #10
Pierre Barbier de Reuille wrote:
[..]
But what is the difference between :
[...]
{
log const & ref = create_tmp();
ref.access();
}
[...]

and :

[...]
{
log val = create_tmp();
val.access();
}
[...]

Besides the fact in the first case you won't be able to modify the
reference ?
In the first case you also won't be able to modify the referred object,
not just the reference. Perhaps you meant that, but I am not sure, and
simply trying to clarify.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 30 '06 #11
Pierre Barbier de Reuille wrote:
But what is the difference between :
The sample you wrote invokes the Return Value Optimization, so there's very
little difference.

References to constant temporaries are useful as arguments:

void foo(std::string const & bar);
...
foo("yo mamma");

Now the string literal will copy-construct a temporary std::string, and bar
will bind to this. And if you pass a real string into foo(), then bar will
efficiently bind to that. foo() is easy to program, without regard to
efficiency.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
Jul 30 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Chris | last post by:
Hello all, I wish to automate printing of PDF documents in a C# application. Is there an Adobe .net object? I tried to create a reference to the COM Object Adobe Type Library, but I get error...
3
by: Roubles | last post by:
Hi All, Here's my problem, I have a bunch of code that passes an allocated object (say obj) to a function, and then dereferences that allocated object when the function returns: foo(obj);...
5
by: Stefan Turalski \(stic\) | last post by:
Hi, I'm wondering if there is a way to send a method parametrs by ref when DataTabel is a type of this value ? I done some sort of select over DataTable columns, just by removing them froma...
1
by: Sherif ElMetainy | last post by:
Hello Using the System.Diagnostics.StackTrace class (see code below), I can know that method that called my currently executing method. Is there a way I can get a reference to the object...
5
by: Mac via DotNetMonster.com | last post by:
Hi all, I have a creating a my own tabpage class (MyTabPage) which inherits the .Net TabPage class. In the relevant event I want to loop through the collection of TabPages and then when I...
2
by: Jeff Brown | last post by:
OK i removed all of my datasets to start fromo scratch again with another method. Is there a way i can create all my datasets in the MDI Parent form and reference them from child forms...
37
by: Greg | last post by:
Except for legacy or non-.NET applications, is there any reason to use VC++ anymore? It seems that for .NET applications, there would be no reason to choose C++ over C# since C# is faster to...
4
by: Bo Peng | last post by:
Dear list, I am looking for a way to store a large amount of unique sequences that will be accessed by objects. The most important operations are: 1. Direct access to the sequences (from...
24
by: Kavya | last post by:
int main (){ int a={{1,2,3},{4,5,6}}; int (*ptr)=a; /* This should be fine and give 3 as output*/ printf("%d\n",(*ptr)); ++ptr;
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.