473,320 Members | 1,846 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,320 software developers and data experts.

References or pointers?

I have made this example:

#include<iostream>

class Beer {
public:
Beer() {
std::cout << "made a beer\n";
num = 1;
}

Beer(int n) : num(n) {}

int getBeer(){
return num;
}

void remove(){
num--;
}

private:
int num;
};

class Brew {
public:
/* Simple*/
void drinkBeer(Beer b) {
std::cout << "Drank " << b.getBeer() << " instances of beers!\n";
b.remove();
}

void checkBeer(Beer b) {
std::cout << b.getBeer() << " instances of beers left!\n";
}


/* With references. Notice that the '&' is placed AFTER the type like the
* pointer operator. */
void drinkBeerRef(Beer& b) {
std::cout << "Drank " << b.getBeer() << " reference beers!\n";
b.remove();
}

void checkBeerRef(Beer& b) {
std::cout << b.getBeer() << " reference beers left!\n";
}

/* With pointers */
void drinkBeer(Beer* b) {
std::cout << "Drank " << b->getBeer() << " pointer beers!\n";
b->remove();
}

void checkBeer(Beer* b) {
std::cout << b->getBeer() << " pointer beers left!\n";
}
};
int main(){

/* (0) Calling default constructor. */
Beer b1;

/* (1) Make a brewery where you can drink! checkBeer will not print
* the right value. */
Beer b2(10); // make 10 beers.
Brew brew;
brew.drinkBeer(b2);
brew.checkBeer(b2);

std::cout << std::endl;
/* (2) Using references */
Beer b3(10); // make 10 beers.
brew.drinkBeerRef(b3);
brew.checkBeerRef(b3);

std::cout << std::endl;

/* (3) Using pointers */

/* Single object containing 10 beers. */
Beer* b4 = new Beer(10);

/* or:
*
* Beer* b4 = new Beer[10];
*
* using default constructor. 10 objects containing 1 beer.
*
* */

brew.drinkBeer(b4);
brew.checkBeer(b4);

return 0;
}
How does passing an argument as a reference differ from passing it as a
pointer (besides from also giving the right result)?

When you use 'new' the data is allocated on the heap and when changed in
a function will remain changed after the functions returns. But this is
also the case with references...does 'Beer b3' allocate 'b3' on the heap?
Sep 5 '07 #1
11 1373

"desktop" <ff*@sss.comha scritto nel messaggio
news:fb**********@news.net.uni-c.dk...
>I have made this example:
....
How does passing an argument as a reference differ from passing it as a
pointer (besides from also giving the right result)?
You can think to references as 'syntax sugar' for const pointers (beware,
not pointer to consts).
Passing an argument by reference is a safer and more convenient way to pass
the pointer to the value.
The callee can modify the value but not the pointer, i.e. can't switch the
'pointer' to something else.
When you use 'new' the data is allocated on the heap and when changed in a
function will remain changed after the functions returns. But this is also
the case with references...does 'Beer b3' allocate 'b3' on the heap?
b3 is on the stack, but the pertinent point is that the section marked /*
Simple*/ it's incorrect.
You pass 'by value' the beer, and that make sense only in the checkBeer
call.

Bye Carlo
Sep 5 '07 #2
On Sep 5, 9:54 am, desktop <f...@sss.comwrote:
I have made this example:

#include<iostream>

class Beer {
public:
Beer() {
std::cout << "made a beer\n";
num = 1;
}

Beer(int n) : num(n) {}

int getBeer(){
return num;
}

void remove(){
num--;
}

private:
int num;

};

class Brew {
public:
/* Simple*/
void drinkBeer(Beer b) {
std::cout << "Drank " << b.getBeer() << " instances of beers!\n";
b.remove();
}

void checkBeer(Beer b) {
std::cout << b.getBeer() << " instances of beers left!\n";
}

/* With references. Notice that the '&' is placed AFTER the type like the
* pointer operator. */
void drinkBeerRef(Beer& b) {
std::cout << "Drank " << b.getBeer() << " reference beers!\n";
b.remove();
}

void checkBeerRef(Beer& b) {
std::cout << b.getBeer() << " reference beers left!\n";
}

/* With pointers */
void drinkBeer(Beer* b) {
std::cout << "Drank " << b->getBeer() << " pointer beers!\n";
b->remove();
}

void checkBeer(Beer* b) {
std::cout << b->getBeer() << " pointer beers left!\n";
}

};

int main(){

/* (0) Calling default constructor. */
Beer b1;

/* (1) Make a brewery where you can drink! checkBeer will not print
* the right value. */
Beer b2(10); // make 10 beers.
Brew brew;
brew.drinkBeer(b2);
brew.checkBeer(b2);
**NO NO NO**
the 2 later lines are syntax errors.You must use the address-of
operator (&) to extract the address of an object and pass it to a
pointer:

brew.drinkBeer(&b2);
brew.checkBeer(&b2);
>
std::cout << std::endl;

/* (2) Using references */
Beer b3(10); // make 10 beers.
brew.drinkBeerRef(b3);
brew.checkBeerRef(b3);

std::cout << std::endl;

/* (3) Using pointers */

/* Single object containing 10 beers. */
Beer* b4 = new Beer(10);

/* or:
*
* Beer* b4 = new Beer[10];
*
* using default constructor. 10 objects containing 1 beer.
*
* */

brew.drinkBeer(b4);
brew.checkBeer(b4);
you can dereference a pointer via the derefrence operator(unary *).try
this one too:

brew.drinkBeerRef( * b4 );
brew.checkBeerRef( * b4 );

beware: you need to get rid of dynamic objects(created via new/new[]
operators) before ending the program :

delete b4;
/* or:
*
* delete[] b4;Beer* b4 = new Beer[10];
*
* if Beer* b4 = new Beer[10];
*
*/
return 0;
>
}

How does passing an argument as a reference differ from passing it as a
pointer (besides from also giving the right result)?

When you use 'new' the data is allocated on the heap and when changed in
a function will remain changed after the functions returns. But this is
also the case with references...does 'Beer b3' allocate 'b3' on the heap?
No,'b3' is allocated on the stack and deallocated(first destructed
then deallocated) prior to exiting the enclosing code block(main
function in this context).

Tip:
Dynamic objects (created with new ) are placed on the heap and live
there unless you do kill them (destroy with delete).
None - static objects declared in code blocks are destroyed when the
enclosing block exits.
Instance data members are destroyed by the owner object.
static objects are destroyed at the end of the program.
pointers can be inc/decremented(++/--) like integral types.this is
usefull when working with intrinsic arrays:

int a[10];
int * ptr =a;//ptr = & a[0];
cout <<*++ptr;//ptr= & a[1];cout<<*ptr;

regards,
FM.

Sep 5 '07 #3
"Carlo Capelli" <ca***********@rdbos.itwrote in message
news:Zb*****************@tornado.fastwebnet.it...
[...]
You can think to references as 'syntax sugar' for const pointers
Indeed.
Sep 5 '07 #4
terminator wrote:
On Sep 5, 9:54 am, desktop <f...@sss.comwrote:
>I have made this example:

#include<iostream>

class Beer {
public:
Beer() {
std::cout << "made a beer\n";
num = 1;
}

Beer(int n) : num(n) {}

int getBeer(){
return num;
}

void remove(){
num--;
}

private:
int num;

};

class Brew {
public:
/* Simple*/
void drinkBeer(Beer b) {
std::cout << "Drank " << b.getBeer() << " instances of beers!\n";
b.remove();
}

void checkBeer(Beer b) {
std::cout << b.getBeer() << " instances of beers left!\n";
}

/* With references. Notice that the '&' is placed AFTER the type like the
* pointer operator. */
void drinkBeerRef(Beer& b) {
std::cout << "Drank " << b.getBeer() << " reference beers!\n";
b.remove();
}

void checkBeerRef(Beer& b) {
std::cout << b.getBeer() << " reference beers left!\n";
}

/* With pointers */
void drinkBeer(Beer* b) {
std::cout << "Drank " << b->getBeer() << " pointer beers!\n";
b->remove();
}

void checkBeer(Beer* b) {
std::cout << b->getBeer() << " pointer beers left!\n";
}

};

int main(){

/* (0) Calling default constructor. */
Beer b1;

/* (1) Make a brewery where you can drink! checkBeer will not print
* the right value. */
Beer b2(10); // make 10 beers.
Brew brew;
brew.drinkBeer(b2);
brew.checkBeer(b2);

**NO NO NO**
the 2 later lines are syntax errors.You must use the address-of
operator (&) to extract the address of an object and pass it to a
pointer:
Well I don't see why its syntactical incorrect. In Brew I have a method
that takes as argument a static object of type Beer.

I use the above lines to illustrate what happens if you DON'T use a
pointer or reference to Beer. The changes made will not be correct after
returning since the remove() call works on a copy of the passed object
and not the actual object.

To achieve the latter its necessary to pass the object as reference or
pointer.
>
brew.drinkBeer(&b2);
brew.checkBeer(&b2);
> std::cout << std::endl;

/* (2) Using references */
Beer b3(10); // make 10 beers.
brew.drinkBeerRef(b3);
brew.checkBeerRef(b3);

std::cout << std::endl;

/* (3) Using pointers */

/* Single object containing 10 beers. */
Beer* b4 = new Beer(10);

/* or:
*
* Beer* b4 = new Beer[10];
*
* using default constructor. 10 objects containing 1 beer.
*
* */

brew.drinkBeer(b4);
brew.checkBeer(b4);
you can dereference a pointer via the derefrence operator(unary *).try
this one too:

brew.drinkBeerRef( * b4 );
brew.checkBeerRef( * b4 );

beware: you need to get rid of dynamic objects(created via new/new[]
operators) before ending the program :

delete b4;
/* or:
*
* delete[] b4;Beer* b4 = new Beer[10];
*
* if Beer* b4 = new Beer[10];
*
*/
return 0;
>}

How does passing an argument as a reference differ from passing it as a
pointer (besides from also giving the right result)?

When you use 'new' the data is allocated on the heap and when changed in
a function will remain changed after the functions returns. But this is
also the case with references...does 'Beer b3' allocate 'b3' on the heap?

No,'b3' is allocated on the stack and deallocated(first destructed
then deallocated) prior to exiting the enclosing code block(main
function in this context).

Tip:
Dynamic objects (created with new ) are placed on the heap and live
there unless you do kill them (destroy with delete).
None - static objects declared in code blocks are destroyed when the
enclosing block exits.
Instance data members are destroyed by the owner object.
static objects are destroyed at the end of the program.
pointers can be inc/decremented(++/--) like integral types.this is
usefull when working with intrinsic arrays:

But a method that takes a reference to a static object will leave the
object changed after returning.
Sep 5 '07 #5
Carlo Capelli wrote:
"desktop" <ff*@sss.comha scritto nel messaggio
news:fb**********@news.net.uni-c.dk...
>I have made this example:
....
>How does passing an argument as a reference differ from passing it as a
pointer (besides from also giving the right result)?

You can think to references as 'syntax sugar' for const pointers (beware,
not pointer to consts).
Passing an argument by reference is a safer and more convenient way to pass
the pointer to the value.
The callee can modify the value but not the pointer, i.e. can't switch the
'pointer' to something else.

Ok thats a very good explanation, thanks!

>When you use 'new' the data is allocated on the heap and when changed in a
function will remain changed after the functions returns. But this is also
the case with references...does 'Beer b3' allocate 'b3' on the heap?

b3 is on the stack, but the pertinent point is that the section marked /*
Simple*/ it's incorrect.
You pass 'by value' the beer, and that make sense only in the checkBeer
call.
I know but the example is also made to show what happens if you DON'T
pass an object as pointer or reference.
Sep 5 '07 #6
On Sep 5, 2:41 pm, desktop <f...@sss.comwrote:
terminator wrote:
On Sep 5, 9:54 am, desktop <f...@sss.comwrote:
I have made this example:
#include<iostream>
class Beer {
public:
Beer() {
std::cout << "made a beer\n";
num = 1;
}
Beer(int n) : num(n) {}
int getBeer(){
return num;
}
void remove(){
num--;
}
private:
int num;
};
class Brew {
public:
/* Simple*/
void drinkBeer(Beer b) {
std::cout << "Drank " << b.getBeer() << " instances of beers!\n";
b.remove();
}
void checkBeer(Beer b) {
std::cout << b.getBeer() << " instances of beers left!\n";
}
/* With references. Notice that the '&' is placed AFTER the type like the
* pointer operator. */
void drinkBeerRef(Beer& b) {
std::cout << "Drank " << b.getBeer() << " reference beers!\n";
b.remove();
}
void checkBeerRef(Beer& b) {
std::cout << b.getBeer() << " reference beers left!\n";
}
/* With pointers */
void drinkBeer(Beer* b) {
std::cout << "Drank " << b->getBeer() << " pointer beers!\n";
b->remove();
}
void checkBeer(Beer* b) {
std::cout << b->getBeer() << " pointer beers left!\n";
}
};
int main(){
/* (0) Calling default constructor. */
Beer b1;
/* (1) Make a brewery where you can drink! checkBeer will not print
* the right value. */
Beer b2(10); // make 10 beers.
Brew brew;
brew.drinkBeer(b2);
brew.checkBeer(b2);
**NO NO NO**
the 2 later lines are syntax errors.You must use the address-of
operator (&) to extract the address of an object and pass it to a
pointer:

Well I don't see why its syntactical incorrect. In Brew I have a method
that takes as argument a static object of type Beer.

I use the above lines to illustrate what happens if you DON'T use a
pointer or reference to Beer. The changes made will not be correct after
returning since the remove() call works on a copy of the passed object
and not the actual object.

To achieve the latter its necessary to pass the object as reference or
pointer.


brew.drinkBeer(&b2);
brew.checkBeer(&b2);
std::cout << std::endl;
/* (2) Using references */
Beer b3(10); // make 10 beers.
brew.drinkBeerRef(b3);
brew.checkBeerRef(b3);
std::cout << std::endl;
/* (3) Using pointers */
/* Single object containing 10 beers. */
Beer* b4 = new Beer(10);
/* or:
*
* Beer* b4 = new Beer[10];
*
* using default constructor. 10 objects containing 1 beer.
*
* */
brew.drinkBeer(b4);
brew.checkBeer(b4);
you can dereference a pointer via the derefrence operator(unary *).try
this one too:
brew.drinkBeerRef( * b4 );
brew.checkBeerRef( * b4 );
beware: you need to get rid of dynamic objects(created via new/new[]
operators) before ending the program :
delete b4;
/* or:
*
* delete[] b4;Beer* b4 = new Beer[10];
*
* if Beer* b4 = new Beer[10];
*
*/
return 0;
}
How does passing an argument as a reference differ from passing it as a
pointer (besides from also giving the right result)?
When you use 'new' the data is allocated on the heap and when changed in
a function will remain changed after the functions returns. But this is
also the case with references...does 'Beer b3' allocate 'b3' on the heap?
No,'b3' is allocated on the stack and deallocated(first destructed
then deallocated) prior to exiting the enclosing code block(main
function in this context).
Tip:
Dynamic objects (created with new ) are placed on the heap and live
there unless you do kill them (destroy with delete).
None - static objects declared in code blocks are destroyed when the
enclosing block exits.
Instance data members are destroyed by the owner object.
static objects are destroyed at the end of the program.
pointers can be inc/decremented(++/--) like integral types.this is
usefull when working with intrinsic arrays:

But a method that takes a reference to a static object will leave the
object changed after returning.- Hide quoted text -
pointers and refrences are both used for passing by reference but they
obey different symantics and have different syntaxes you can not
initialize a pointer with a normal variable or vice-versa:

class A{};
A a1
A * Aptr=a1;//error
A a2=Aptr;//error
A & Aref1=Aptr;//error

you must write:

A * Aptr= & a1;//pass the address of 'a1' to 'Aptr'
A a2= * Aptr ;//pass the value pointed by 'Aptr' to 'a2'
A & Aref1= a1;//make 'Aref1' an aliase(new name)for 'a1'
A & Aref2= *Aptr;//make 'Aref2' a reference to what 'Aptr' points to

you seem not to know the meaning of 'static';read your book before
asking any more Qs.

FM.
Sep 5 '07 #7
On Wed, 05 Sep 2007 02:46:08 -0700, Chris Thomasson wrote:
>You can think to references as 'syntax sugar' for
const pointers

Indeed.
Not always true.
The compiler is able to "inline" access by reference
so that it access the original value directly.

--
SasQ
Sep 5 '07 #8
On Sep 5, 9:46 pm, "Chris Thomasson" <cris...@comcast.netwrote:
"Carlo Capelli" <carlo.cape...@rdbos.itwrote in message
You can think to references as 'syntax sugar' for const pointers

Indeed.
If you like fostering misconceptions about the language, that is.

Sep 5 '07 #9
"Old Wolf" <ol*****@inspire.net.nzwrote in message
news:11**********************@50g2000hsm.googlegro ups.com...
On Sep 5, 9:46 pm, "Chris Thomasson" <cris...@comcast.netwrote:
>"Carlo Capelli" <carlo.cape...@rdbos.itwrote in message
You can think to references as 'syntax sugar' for const pointers

Indeed.

If you like fostering misconceptions about the language, that is.
Okay: I am wrong.

Sep 6 '07 #10
"SasQ" <sa***@go2.plwrote in message
news:pa****************************@go2.pl...
On Wed, 05 Sep 2007 02:46:08 -0700, Chris Thomasson wrote:
>>You can think to references as 'syntax sugar' for
const pointers

Indeed.

Not always true.
The compiler is able to "inline" access by reference
so that it access the original value directly.
I was thinking in the sense that a reference wraps an underlying constant
pointer which points directly at the object.

Sep 6 '07 #11
"Chris Thomasson" <cr*****@comcast.netwrote in
news:rY******************************@comcast.com:
"SasQ" <sa***@go2.plwrote in message
news:pa****************************@go2.pl...
>On Wed, 05 Sep 2007 02:46:08 -0700, Chris Thomasson wrote:
>>>You can think to references as 'syntax sugar' for
const pointers

Indeed.

Not always true.
The compiler is able to "inline" access by reference
so that it access the original value directly.

I was thinking in the sense that a reference wraps an underlying
constant pointer which points directly at the object.

In many cases, references are to objects as typedefs are to types. What
I mean is that a reference adds an alias to an existing object. What
lies under the covers can vary quite a bit. For example:

int f( object const & obj)
{
// In this form, obj most often is a hidden pointer, but with
// inlining a such, that may not be true either
}
int a;
int & b = a;

In the above form, most compilers won't have any backing for b at all
and will generate code as if you had just used 'a'. What adds to the
confusion is that in Java or C# they use references as pointers. That
is:

Object a = new Object;

a = new Object;

Works fine with the assignment changing the object that a points to and
the first object is lost to the garbage collector. In C++ If you wrote:

Object & a = *new Object;
a = *new Object;

You would have created a second new object and copied its contents on
top of the first object, then orphaned the second. That is, you can't
reseat references in C++. If you wanted the Jave/C# behavior, then you
would use pointers. That is what they are for. C++ doesn't hide the
mechanics from you and if you are trying to squeeze every clock cycle
out of your program, that is a good thing.

Hope that helps more than confuses.

joe
Sep 6 '07 #12

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

Similar topics

17
by: Tom | last post by:
The motivation for references seems clear: stop people from using nasty pointers when all they really want is a reference to an object. But C++ references are so inadequate that I'm still using...
15
by: Web Developer | last post by:
Hi, Can someone provide a short and concise statement(s) on the difference between pointers and references. A graphical representation (via links?) of both would be much appreciated as well. ...
8
by: john townsley | last post by:
are there any differences when using pointers or passing by reference when using 1) basic variables 2)complex variable types like arrays,structures it seems easier to simply pass by reference...
11
by: codebloatation | last post by:
I know how to use references but i DO not get WHY they exist other than to add to the language. Are they actually needed for anything?
458
by: wellstone9912 | last post by:
Java programmers seem to always be whining about how confusing and overly complex C++ appears to them. I would like to introduce an explanation for this. Is it possible that Java programmers...
28
by: Frederick Gotham | last post by:
When I was a beginner in C++, I struggled with the idea of references. Having learned how to use pointers first, I was hesitant to accept that references just "do their job" and that's it. Just...
9
by: igor.kulkin | last post by:
References is a relatively basic feature of C++ language. It might be a good thing to think of references as aliases to the variables. However it's good to think of references this way when you...
76
by: valentin tihomirov | last post by:
As explained in "Using pointers vs. references" http://groups.google.ee/group/borland.public.delphi.objectpascal/browse_thread/thread/683c30f161fc1e9c/ab294c7b02e8faca#ab294c7b02e8faca , the...
1
by: sip.address | last post by:
Hi everyone, A while ago I asked for help about using smart pointers (ie. shared_ptr) in cyclic situations. Weak ptrs popped out and I gave it a try, but to be honest, I don't feel very...
19
by: MQ | last post by:
Can someone tell me where I should use pointers and where I should use references? In his book, Stroustrup says that you should use pointers for passing arguments that are to be modified, not...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.