473,387 Members | 1,502 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 reference ?


Hi,

References introduced make things much more complicated. e.g.

int a;
void f(int &n);
void g(int *p);

Isn't g(&a) much more clear than f(a), when we would change the value of
the lvalue a ?

Are there any efficiency differences ?

Is reference a must in c++ ?

thanks.

--
William Xuuu
Jul 22 '05 #1
28 2099
William Xuuu wrote:

Hi,

References introduced make things much more complicated. e.g.

int a;
void f(int &n);
void g(int *p);

Isn't g(&a) much more clear than f(a), when we would change the value of
the lvalue a ?
Clearity is in the eye of the beholder :-)
Seriously. It depends. In your above example it definitly is
not clear to the caller if

f(a)

will change 'a' or not.

But in practice this is much less an issue then you think. Mostly
because in real life functions are not called 'f' and arguments are
not called 'a'. In

j = CalcFibonacci( InputNumber );

will the function CalcFibonacci alter the passed argument? While
there is no 100% guarantee, bets are good, that it won't.

Same for eg. the prototype

void Deposit( Account& TheAccount, long Amount );

Now guess: Will The Account be changed when the function is called.
If you read the callers code:

Account CustomerAccount;
long Amount;

CustomerAccount = AskForCustomer();
Amount = AskForAmount();

Deposit( CustomerAccount, Amount );

When you read that code, and have no idea that the first argument
to Deposit is passed by reference, would you expect CustomerAccount
to change? Sure I would! If I deposit something on an account, then
the amount associated with that account changes.

Are there any efficiency differences ?
When you pass a pointer, it is the functions responsibility to at
least check that the passed pointer is not 0. On the other hand,
if you pass per reference AND the function gets inlined, you open
a lot of possibilities for the compiler for optimizations.

Is reference a must in c++ ?


Yes. Otherwise writing custom operators would not be possible.
Granted, we could live without that feature (although it is a
nice one) and then AFAIK there would be no killer argument for
not dropping references.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #2
William Xuuu <wi**********@163.com> writes:

Hi, References introduced make things much more complicated. See
http://www.parashift.com/c++-faq-lite/references.html
Is reference a must in c++ ?

In some situations, yes I think so.
Jul 22 '05 #3
>
Are there any efficiency differences ?

Is reference a must in c++ ?


Reference variables can be created for local use as aliases
for other variables within a function. Reference variables must
be initialized in their declarations, and they cannot be reassigned
as aliases to other variables. Once a reference variable is
declared as an alias for another variable, all operations performed
on the alias actually are performed on the variable.
As a former java-coder I can say that pointers are needless :-)

Thomas B.
Jul 22 '05 #4
Hi William,
Isn't g(&a) much more clear than f(a), when we would change
the value of the lvalue a ?

Are there any efficiency differences ?


If a function has to change a variable via a pointer, the function
has to check for null-pointers first. For example...

void Change(int* pVal)
{
if(pVal)
*pVal = 123;
else
throw SomeException;
}

Okay, but perhaps you are writing a function where it is
not allowed to pass null-pointers as parameters. In this
case you have to add some documentation to your function
where this pre-condition is described. You should still
use assert() before accessing the pointer, though...

With references all this is not necessary. If you declare
a function like...

void Change(int& val);

....then it is simply not possible to call this function with a
null-pointer.

Tilman

Jul 22 '05 #5

"William Xuuu" <wi**********@163.com> wrote in message
news:87************@163.com...

Hi,

References introduced make things much more complicated. e.g.

int a;
void f(int &n);
void g(int *p);

Isn't g(&a) much more clear than f(a), when we would change the value of
the lvalue a ?

Are there any efficiency differences ?

Is reference a must in c++ ?


Try writing an assignment operator using a pointer.

class X
{
X& operator=(const X* rhs);
};

Then you would then have to write

X x, y;
x = &y;

Do you think that is good style?

References and pointers are different. The main difference is that a
reference once initialised cannot be made to refer to something else. This
is often exactly what you want, and makes using references very common, it
also makes the syntax simpler.

john
Jul 22 '05 #6

As a former java-coder I can say that pointers are needless :-)


double GetFirstNegative(double* pNums)
{
while(*pNums>0.0) ++pNums;
return *pNums;
}

Try that with references and compare the assembly generated.
Jul 22 '05 #7
Gernot Frisch wrote:

double GetFirstNegative(double* pNums)
{
while(*pNums>0.0) ++pNums;
return *pNums;
}

Try that with references and compare the assembly generated.


How about:

double GetFirstNegative(double* pNums)
{
int i=0;
while(pNums[i]>0.0)
++i;
return pNums[i];
}

No pointers, no references. Agreed, has an extra variable.

It is very rare in C++ that a pointer is truly needed. Almost all the
time you can get around using references or [].
--
X-Privat Project - http://www.newsserver.it/
Jul 22 '05 #8
Hi

double GetFirstNegative(double* pNums)
{
int i=0;
while(pNums[i]>0.0)
++i;
return pNums[i];
}


Pointer free, array passed by reference

double getFirstNegative(double arr[]) {
Thomas B.

Jul 22 '05 #9
In article <87************@163.com>,
William Xuuu <wi**********@163.com> wrote:

References introduced make things much more complicated. e.g.


That depends on your point of view. :-)

I came to C++ from Fortran and Pascal, which use reference semantics
(although not the same syntax as C++ of course) for passing data to
functions. I find references to be natural to use, whereas pointers are
cumbersome and error-prone.

--
Jon Bell <jt*******@presby.edu> Presbyterian College
Dept. of Physics and Computer Science Clinton, South Carolina USA
Jul 22 '05 #10
And you should always consider the size of an array

double getFirstNegative(double arr[], int &iSize) {
double dValue = 0.0;
for (int i = 0; i < iSize && dValue == 0.0; i++) {
if(arr[i] < 0.0) dValue = arr[i];
}
return dValue;
}

I am not a friend of code compression :-) Your code versions
would throw an OutOfBound-exception

Thomas B.
Jul 22 '05 #11
William Xuuu wrote:
int a;
void f(int &n);
void g(int *p);

Isn't g(&a) much more clear than f(a), when we would change the value of
the lvalue a ?


Yes, but if you name the function evaluate_something instead of f things
will be much more clear.

--
Salu2
Jul 22 '05 #12

"Julián Albo" <JU********@terra.es> wrote in message
news:2v*************@uni-berlin.de...
William Xuuu wrote:
int a;
void f(int &n);
void g(int *p);

Isn't g(&a) much more clear than f(a), when we would change the value of
the lvalue a ?


Yes, but if you name the function evaluate_something instead of f things
will be much more clear.


For example:

std::cin >> a;

Isn't this clearer than having to write

std::cin >> &a;

?
Jul 22 '05 #13
John Harrison wrote:
References and pointers are different. The main difference is that a
reference once initialised cannot be made to refer to something else.


....and perhaps equally important (as several posters have pointed out),
a reference *must* be initialised.

And hence may be assumed to refer to something sensible... oops, maybe
not:

int* p = new int(5);
int& i = *p;
delete p;

I note that the following program:

<CODE>

#include <iostream>

int main()
{
int* p = new int(5);
int& i = *p;
std::cout << "i = " << i << '\n';
delete p;
p = new int(6);
std::cout << "i = " << i << '\n';
delete p;
return 0;
}

</CODE>

outputs:

i = 5;
i = 6;

on my system - but I suspect that this is actually UB and it is
fortuitous that the second new allocated the same address as the
first...

--
Lionel B

Jul 22 '05 #14
Thomas Barth wrote:
And you should always consider the size of an array

double getFirstNegative(double arr[], int &iSize) {
double dValue = 0.0;
for (int i = 0; i < iSize && dValue == 0.0; i++) {
if(arr[i] < 0.0) dValue = arr[i];
}
return dValue;
}

I am not a friend of code compression :-) Your code versions
would throw an OutOfBound-exception

Thomas B.


I was replying to Gernot's post. I made as minimal changes as possible
to the program to get to it work without pointers.

Actually, my code will not throw any exception, the whole thing will
just crash. On Linux, probably the famous "Segmentation fault. Core dumped."

-Arijit
Jul 22 '05 #15

Actually, my code will not throw any exception, the whole thing will just crash. On Linux, probably the famous "Segmentation
fault. Core dumped."


It's embarrassing that a coder presents code that "just crashs". Do you know
exception handling? Remember, the topic of this thread-child is that pointers
are needless. You showed us a crashy solution with a pointer.
Shake your head and wake up!

Thomas B.

Jul 22 '05 #16
Thomas Barth wrote:
Actually, my code will not throw any exception, the whole thing will just crash. On Linux, probably the famous "Segmentation
fault. Core dumped."

It's embarrassing that a coder presents code that "just crashs". Do you know
exception handling? Remember, the topic of this thread-child is that pointers
are needless. You showed us a crashy solution with a pointer.
Shake your head and wake up!

Thomas B.


I know exception handling. The point is that no exceptions will be
thrown in this case. And I showed a solution without explicit pointers.
No out-of-bound exception will be generated, even when you access
elements outside the array bounds.

And you miss the whole point of my reply. The message I replied to had
this ->
double GetFirstNegative(double* pNums)
{
while(*pNums>0.0) ++pNums;
return *pNums;
}

Try that with references and compare the assembly generated.
Which I changed to ->
double GetFirstNegative(double* pNums)
{
int i=0;
while(pNums[i]>0.0)
++i;
return pNums[i];
}

No pointers, no references. Agreed, has an extra variable.


I probably should have written double GetFirstNegative(double pNum[]),
but thats besides the point. What I tried to do was the change the code
already posted to work without pointers, while keeping the structure of
the original code unaltered. Thats why I did not use range checking,
because the original code didn't have it. And the way the code is
written, range checking is unnecessary if you use sentinels.
-Arijit

Jul 22 '05 #17
>
I probably should have written double GetFirstNegative(double pNum[]), but thats besides the point. What I tried to do was the
change the code already posted to work without pointers, while keeping the structure of the original code unaltered. Thats why I
did not use range checking,


Who said to keep the structure of the code? :-) Of course you have
to change the programming style as well, if you want to pass on pointers.
That's the deal with it.

Have a nice evening :)

Thomas B.

Jul 22 '05 #18
> Are there any efficiency differences ?

Do you check the pointer in g() for a non-zero value?
This safety check can be avoided and omitted by the passing of the
arguments by reference.
Jul 22 '05 #19
"Thomas Barth" <th******@mail.isis.de> wrote:
Arijit wrote:

double GetFirstNegative(double* pNums)
{
int i=0;
while(pNums[i]>0.0)
++i;
return pNums[i];
}

No pointers, no references. Agreed, has an extra variable.

This still uses a pointer. pNums is a pointer. The fact that
there is no '*' symbol in the code does not change this.
pNums[i] is the same as: *(pNums + i)
Pointer free, array passed by reference

double getFirstNegative(double arr[]) {


In this case, arr is a pointer. This is identical to the
original declaration.

To pass an array by reference you need to write:
double foo( double (&arr)[10] )
Jul 22 '05 #20
William Xuuu wrote:
References introduced make things much more complicated. e.g.

int a;
void f(int &n);
void g(int *p);
Don't do that!

Pass by value, const reference or const pointer
and return by value:

int f(const int& n) {
return n + 1;
}

int g(const int* p) {
return *p + 1;
}
Isn't g(&a) much more clear than f(a),
When we would change the value of the lvalue a?

Are there any efficiency differences?

Is reference a must in C++?

Jul 22 '05 #21
"John Harrison" <jo*************@hotmail.com> writes:
Try writing an assignment operator using a pointer.

class X
{
X& operator=(const X* rhs);
};

Then you would then have to write

X x, y;
x = &y;

Do you think that is good style?
Hmm, i see your point. But the assignment operator is different from a
general method, we don't generally call it as x.operator=(&y). Meanwhile in
my e.g., i'd say g(&a) is better than f(a), right? So, there are some
things in c++ that reference performs more elegant than pointer, not
all. That's all.
References and pointers are different. The main difference is that a
reference once initialised cannot be made to refer to something else. This
is often exactly what you want, and makes using references very common, it
also makes the syntax simpler.


One has to master two things now, compared with one before. I can't agree.

--
William Xuuu
Jul 22 '05 #22
Hi,
I am new to C++.
In Java, it is possible to define one class to be "final" so no other
class can inherit it.
I am wondering whether or not there is some mechanism in C++ do the same
job. Besides putting all constructors privte, any other solution?
Jul 22 '05 #23
"Cheng Mo" <mo******@com.motorola> wrote...
I am new to C++.
In Java, it is possible to define one class to be "final" so no other
class can inherit it.
I am wondering whether or not there is some mechanism in C++ do the same
job. Besides putting all constructors privte, any other solution?


http://www.research.att.com/~bs/bs_f...#no-derivation
Jul 22 '05 #24
>
References and pointers are different. The main difference is that a
reference once initialised cannot be made to refer to something else.
This
is often exactly what you want, and makes using references very common,
it
also makes the syntax simpler.


One has to master two things now, compared with one before. I can't agree.


Fair enough, you're free not to use the parts of C++ that don't appeal to
you. You can just use them for parameters to overloaded operators and copy
constructors (where they are essential).

It took me along while to get used to references but now I use them all the
time.

john
Jul 22 '05 #25
William Xuuu <wi**********@163.com> wrote in message news:<87************@163.com>...
Hi,

References introduced make things much more complicated. e.g.

int a;
void f(int &n);
void g(int *p);

Isn't g(&a) much more clear than f(a), when we would change the value of
the lvalue a ?

Are there any efficiency differences ?

Is reference a must in c++ ?

thanks.


The reason that Stroustup introduced references into C++ was actually
operator overloading.
For example, in the assignment operator, the return type must be a
reference.
Jul 22 '05 #26
Cheng Mo <mo******@com.motorola> wrote in message news:<cn**********@avnika.corp.mot.com>...
Hi,
I am new to C++.
In Java, it is possible to define one class to be "final" so no other
class can inherit it.
I am wondering whether or not there is some mechanism in C++ do the same
job. Besides putting all constructors privte, any other solution?


// put this in header file:
// header_file.h
// -----------------------------
#ifndef HEADER_FILE_H
#define HEADER_FILE_H
class BaseOfFinalClass{
public:
// ...some interface functions eg
virtual void function1()=0;
virtual ~BaseOfFinalClass(){}
};

BaseOfFinalClass* makeFinalClass();
#endif
// ------------------------------

// put your final class in implementation file:

// implementation_file.cpp
// ------------------------
#include "header_file.h"
class FinalClass: public BaseOfFinalClass{
public:
// ... implementation functions
virtual void function1(){ /* ... */ }
};

BaseOfFinalClass* makeFinalClass()
{
return new FinalClass;
}
// ------------------------

Greetings, Bane.
Jul 22 '05 #27
Old Wolf wrote:
"Thomas Barth" <th******@mail.isis.de> wrote:
Arijit wrote:

double GetFirstNegative(double* pNums)
{
int i=0;
while(pNums[i]>0.0)
++i;
return pNums[i];
}

No pointers, no references. Agreed, has an extra variable.

This still uses a pointer. pNums is a pointer. The fact that
there is no '*' symbol in the code does not change this.
pNums[i] is the same as: *(pNums + i)
I meant no explicit pointers are used. I indeed tried to write the
program without * . I consider using [] to dereference a pointer not
using pointers. You can never eliminate implicit pointers. For example,
references are usually implemented as pointers.
Pointer free, array passed by reference

double getFirstNegative(double arr[]) {


This was not written by me.
In this case, arr is a pointer. This is identical to the
original declaration.

To pass an array by reference you need to write:
double foo( double (&arr)[10] )


Yes. But will there be any difference in usage of arr in the two cases ?

-Arijit
Jul 22 '05 #28
Cheng Mo wrote:
Hi,
I am new to C++.

I think you are new to newsgroups as well, as you posted your
completely irrelevant message in reply to someone else. Learn how to
use Thunderbird to start new threads rather than piggy-back on existing
ones.

Brian
Jul 22 '05 #29

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

Similar topics

2
by: RU | last post by:
Hi, I am working on a porting project to port C/C++ application from unixware C++, AT&T Standard components to g++ with STL on Linux. This application has been working properly on...
110
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object...
11
by: Doug | last post by:
Is there any harm in passing an object into a method with the 'ref' keyword if the object is already a reference variable? If not, is there any benefit?
13
by: Abe Frohnman | last post by:
Hello all, I'm passing a reference to a class into the constructor of a form, like so: public MyForm(int count, ref Area myArea) {...} How can I use myArea outside the constructor? Should I...
4
by: z_learning_tester | last post by:
I'm reading the MS press C# book and there seems to be a contradiction. Please tell me which one is correct, 1 or 2. Thanks! Jeff 1. First it gives the code below saying that it prints 0 then...
13
by: al.cpwn | last post by:
I get that these two are different int* get() { static int m; return &m; } int& get() {
51
by: Kuku | last post by:
What is the difference between a reference and a pointer?
27
by: David W | last post by:
I'm almost tearing my hair out. A colleague claimed that a null reference can exist, like this: void f( int& p ) { printf( "%d\n", p ); } int main (int argc, char *argv) {
41
by: Summercool | last post by:
Can we confirm the following? also someone said, Java also has "reference" like in C++, which is an "implicit pointer": Pointer and Reference --------------------- I am starting to see what...
275
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
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...
0
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,...
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.