473,804 Members | 2,261 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1534
On 29 Jul 2006 11:39:53 -0700, "sarathy" <sp*********@gm ail.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 << "constructi on" << std::endl;
}

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

~log ( void ) {
std::cout << "destructio n" << 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************ **********@75g2 000cwc.googlegr oups.com>,
"sarathy" <sp*********@gm ail.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******@earth link.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.c om
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

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

Similar topics

8
12596
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 "Exception from HRESULT 0x80131019" Thanks Chris
3
1387
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); obj->foobar = TRUE; The issue is that foo *might* free obj. So the dereference can be
5
10094
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 table is each of them isn't on a stirng, but right no I have to do it in a wat of: 1. passing DataTable to method (lets call it SelectOverDataTabel) 2. declare a local (in SelectOver...) DataTable, inicialize it with my value
1
1049
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 instance used to call the method, i.e. the this pointer for the calling method? I searched the FCL documentation for such a method, but I didn't find any. Do I have to use Unmanaged code? public class C2 { public static void M1()
5
1662
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 find the TabPage I am after I want to cast this to MyTabPage so that I can access the properties that I have added to this class. When I try to do this I get an "invalid cast" error at runtime. Am I not able
2
1403
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 ******************* for instance i just created dsName1 in the MDi Parent and the dsName.xsd was created in the solution. Now i want 2 different child forms to be able to access certain data
37
2161
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 develop with (i.e. no header files, objects are easier to create and use, C# language is native to .NET) I'm sure this question will stir some emotions :-) -- Greg McPherran www.McPherran.com
4
3163
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 pointers stored in each object). Access through key lookup is not acceptable. 2. Given a new sequence, determine if it is already in the factory of sequences. If so, increase the reference count of the existing sequence
24
1967
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
9714
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10599
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10346
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10347
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10090
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9173
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5531
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4308
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.