473,748 Members | 5,242 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++: can someone explain to me, a C/Hw guy, what the diff is between a reference (&) and a pointer?

bo
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...

TIA

Jul 22 '05 #1
14 2538

"bo" <bo@cephus.co m> wrote in message
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...


http://www.parashift.com/c++-faq-lit...s.html#faq-8.6

Sharad
Jul 22 '05 #2
bo wrote:
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...

References are more easy to be optimised out.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #3
Sharad Kala wrote:
http://www.parashift.com/c++-faq-lit...s.html#faq-8.6


I do not find that FAQ particularly useful. More accurately I believe it
is full of (nicely termed) nonsense.

Do you consider it useful?

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #4

"Ioannis Vranos" <iv*@guesswh.at .grad.com> wrote in message > Sharad Kala
wrote:
http://www.parashift.com/c++-faq-lit...s.html#faq-8.6


I do not find that FAQ particularly useful. More accurately I believe it
is full of (nicely termed) nonsense.
Do you consider it useful?


Well, I think they could have been little more clearer (considering it's
FAQ). Basically references are preferred when one knows that one needs to
refer to the same object and that won't change. In fact it's quite possible
that compilers implement references in terms of T* const. Also references
offer the advantage that you don't need to check for null-ness so many if
loops are avoidable.

Sharad


Jul 22 '05 #5
bo posted:
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some actual difference that makes references different and or preferable over pointers in some cases...

TIA

References are nicer to work with, in that they behave
exactly like real variables.

Pointers are... different...

As I always I prefer the more familiar. Here's what I do:

A) Use a references. If I can't... go to plan B.

B) Use a pointer.
The only advantage references have over pointers is that
they behave exactly like your familiar variables. (Some
people may also argue that you're guaranteed that they
refer to a legitimate object, I don't buy this though...)

The advantage that pointers have over references are:

a) They can be reseated. One minute they can point East,
the next South West.

b) They can be incremented/decremented. If you have a
pointer to a character, you simply increment it and it
points to the next character in the string.

So...

Use references. If you can't, eg. you need to increment it
or seseat it, then *resort* to pointers.
-JKop
Jul 22 '05 #6
bo wrote:
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...

TIA


"Use references when you can, use pointers when you must" is my mantra.

Under the hood, both references and pointers are implemented using
pointers. Semantically however, references are "bound" to specific
variables, and do not "point" to arbitrary variables. That probably sums
up the difference between the two entities.

Using references makes my code cleaner and less error-prone because I
cannot manipulate a reference in such away that it "points" away from
the intended variable.

Using references also allows me to change a pass-by-value parameter to a
pass-by-reference without modifying the calling code. Consider these
function prototypes:

void Function_A(cons t Large_Class in);
void Function_B(cons t Large_Class& in);

These two functions are called in exactly the same way--Function_A(obj) ,
Function_B(obj) . But the resulting calls are quite different. References
allow me to change the parameter-passing method as I develop my code
with minimal impact.
Jul 22 '05 #7
On Thu, 16 Sep 2004 07:32:44 -0500, bo <bo@cephus.co m> wrote:
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...


Pointers are not suitable for operator overloading. Use
references in that case.

You cannot use references in standard containers. E.g. you must
write vector<X*> instead of vector<X&>. Use pointers in that
case.

References are guaranteed to refer to something. They cannot be
null. Use references unless you need the null value.

A reference cannot be reseated to another object. Use references
unless you need pointer arithmetic.

If a function modifies its argument, some programmers feel that
pointers are better because it makes it obvious that the arg can
be changed: f(&i)
Other programmers use a reference but choose a self-explicit
function name: modify(i)

Can't think of anything else right now...

Check
http://www.research.att.com/~bs/bs_f...and-references
And also, of course, section 8 of this newsgoup's FAQ.

--
Andre Heinen
My address, rot13-encoded: n qbg urvara ng rhebcrnayvax qbg pbz
Jul 22 '05 #8
Added to what everyone else has said, it is also important to understand the
implication of ownership when deciding whether to use a reference or a
pointer.

Pointer are generally used to take ownership ( responsible for deleting it
if it was new'd ) of an object, whereas a reference would be use when
someone else has ownership of the object.

While you could implement the "ownership/non-ownership" using a pointer in
both cases, it does make the code self documenting, and lets the compiler
check for bugs :-)

HTH
-Steve

"bo" <bo@cephus.co m> wrote in message
news:9q******** *************** *********@4ax.c om...
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...

TIA

Jul 22 '05 #9
* Ioannis Vranos:
Sharad Kala wrote:
http://www.parashift.com/c++-faq-lit...s.html#faq-8.6


I do not find that FAQ particularly useful. More accurately I believe it
is full of (nicely termed) nonsense.

Do you consider it useful?


The FAQ explained:
<q>Use references when you can, and pointers when you have to.</q>

Explanation: if you can use a reference, use a reference.

Otherwise, use a pointer.

This is good advice because references are more limited than pointers, so to
screw up you have to work much harder at it when all you have is a reference.

<q>References are usually preferred over pointers whenever you don't need
"reseating" </q>

Explanation: if you don't need to let the same variable refer to different
objects at different times, you can probably use a reference, and so you
should probably use a reference.
<q>This usually means that references are most useful in a class's public
interface.</q>

Explanation: the public interface of a class let's you pass information into
and get information out of an object. Unless there is a need for a logical
null-value this can be done using references. Hence use references here.
<q>References typically appear on the skin of an object, and pointers on the
inside.</q>

Explanation: in the code that implements an object pointers may be needed
because there one may need to let the same variable refer to different objects
at different times, or handle logical null-values. For example, in a linked
list class you need pointers inside. But the interface can be and probably
should be expressed with references only, giving the client code existence
guarantees that greatly simplifies the client code.
<q>The exception to the above is where a function's parameter or return value
needs a "sentinel" reference.</q>

Explanation: this is the logical null-value referred to above.
<q>This is usually best done by returning/taking a pointer, and giving the
NULL pointer this special significance (references should always alias
objects, not a dereferenced NULL pointer).</q>

Explanation: here Marshall Cline is expressing an opinion, which e.g. Bertrand
Meyer (the Eiffel man) seems to be diametrically opposed on. I'm personally
somewhere in between, choosing whatever seems most practical. But I think I
mostly lean in the direction Marshall is pointing here: it's too cumbersome to
have isVoid() functions, especially since a functional interface isn't
something that usually can be passed further around as data, as a pointer can.
<q>Note: Old line C programmers sometimes don't like references since they
provide reference semantics that isn't explicit in the caller's code.</q>

Explanation: people often do things out of habit and then rationalize it by
inventing reasons. Flame wars have therefore been fought over whether an "&"
in the client code indicates -- or not -- that an actual argument is an
out or an in/out (as opposed to pure in) argument. The facts are (1) that "&"
in the client code tells you nothing, (2) that in the C language the lack of
"&" tells you that argument is pure in, and (3) that in C++ the lack of "&"
doesn't tell you anything, either: you need to know about the function called.
<q>After some C++ experience, however, one quickly realizes this is a form of
information hiding, which is an asset rather than a liability.</q>

Explanation: this is not a technical comment but a methodological one. I
happen to agree with Marshall here but it's not universally agreed on. Anyway
the only connection to C++ is that the "&"-issue is a concrete example.
<q>E.g., programmers should write code in the language of the problem rather
than the language of the machine.</q>

Explanation: same as the previous one.

--
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 22 '05 #10

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

Similar topics

71
4332
by: ROSY | last post by:
1. How would you use the functions memcpy(), memset(), memmove()?
9
6519
by: Ching-Lung | last post by:
Hi all, I try to create a tool to check the delta (diff) of 2 binaries and create the delta binary. I use binary formatter (serialization) to create the delta binary. It works fine but the delta binary is pretty huge in size. I have 1 byte file and 2 bytes file, the delta should be 1 byte but somehow it turns out to be 249 bytes using binary formatter. I guess serialization has some other things added to the delta file.
14
2513
by: Robin Tucker | last post by:
Although I've been working on this project for 8 months now, I'm still not sure of the difference between ByVal and ByRef. As most objects in VB are reference types, passing ByVal I've discovered allows me to store a reference to the object I passed by val, to change that object and for the change to be reflected in the callers copy of the reference (confused?). Well, what is byref for in that case? I'm coming from a C++ background...
18
3532
by: man | last post by:
can any one please tell me what is the diff between pointer and reference.....and which one is better to use ....and why???????
17
1941
by: Rob Hoelz | last post by:
I've been compiling a list of the differences between C and C++, and I'd like to see how thorough I've been. Could any of you go over this list and see if I've missed anything? Here's the list: Mid-scope declarations Default function parameters new/delete operators Better implementation of const
7
8222
by: Jo | last post by:
Hi, How can i differentiate between static and dynamic allocated objects? For example: void SomeFunction1() { CObject *objectp = new CObject; CObject object;
4
1317
by: panks | last post by:
What is diff between Class c=new Class(); //Create object and Class c; c=new Class(); //create reference variable
0
8826
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9366
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...
0
9241
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
8239
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
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4597
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
4867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3303
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
3
2211
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.