473,320 Members | 1,857 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.

Understanding of Pointers and References

Nepomuk
3,112 Expert 2GB
Hi!
I'm learning C++ and have just read about Pointers and References a bit. Now I'm not absolutely sure, that I've understood it correctly.

I asume, that (taking an example from the real world) "nepomuk" would be a reference to me, and I could have further references like "other_name" or so, that also refer to me. And of course, if you would annoy "other_name", it would also affect "nepomuk".
Expand|Select|Wrap|Line Numbers
  1. person nepomuk = new person(...);
  2. person & other_name = nepomuk;
  3. other_name.annoy();
  4.  
  5. => nepomuk.isAnnoyed() == true
At the same time, my coordinates (say 5.266007882805498, -31.9921875) would be a pointer to my position? So, if you send a letter to these coordinates, I will get it. (By the way, those coordinates are somewhere in the Atlantic Ocean between Africa and South America and NOT my actual position.)
Expand|Select|Wrap|Line Numbers
  1. person nepomuk = new person(...);
  2. person * coordinates;
  3. coordinates = &nepomuk;
  4. sendLetterTo(coordinates);
  5.  
  6. => nepomuk.recievesLetter() == true
Is that correct?

Greetings,
Nepomuk


Edit: Acording to the "Full list of Code Tag Supported Languages", that code should be formatted. I used code=cpp. However, it says "code (text)" instead and isn't formatted at all. Has the system been changed?
Here a few other tests:
Expand|Select|Wrap|Line Numbers
  1. public class Test {
  2. public static void main(String[] args)
  3. {
  4. System.out.println("This is Java");
  5. }
  6. }
Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3. <title>HTML</title>
  4. </head>
  5. <body>
  6. <h1>This is HTML</h1>
  7. </body>
  8. </html>
Expand|Select|Wrap|Line Numbers
  1. #include <iostream.h>
  2. int main(){
  3. printf("This should be C");
  4. }
This used to work. How weird...
Jun 16 '08 #1
5 1843
oler1s
671 Expert 512MB
Your last block of code is broken. It’s <iostream>, not <iostream.h>. printf is from the C library <cstdio> not <iostream> .

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5.     std::cout << “This is C++”;
  6. }
  7.  
Jun 16 '08 #2
Banfa
9,065 Expert Mod 8TB
Generally pointers and references do similar things. In C+ it is considered preferable to use references if possible in large part because it is much much harder (but not impossible) to create an invalid reference than it is to create an invalid pointer.

They are both methods of referring to an object indirectly, a reference is the object where as a pointer is the address of the object. The examples you give are reasonable.

1 important difference is that references must be initialised when the are declared where as pointers do not have to be. However a pointer must be initialised to point to a valid object before it is dereferenced otherwise you will invoke undefined behaviour (which is bad). In fact this ability to declare pointers without initialising them and to have invalid pointers is, I suspect, one of the reasons that references where introduced into C++. It is quite a lot harder to go wrong with a reference than a pointer.


The code tags have changed, the previous code was buggy and holding up site development so it was removed. This is temporary and it will change again so keep putting in the language markers they may be used again someday.
Jun 16 '08 #3
Nepomuk
3,112 Expert 2GB
Your last block of code is broken. It’s <iostream>, not <iostream.h>. printf is from the C library <cstdio> not <iostream> .

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5.     std::cout << “This is C++”;
  6. }
  7.  
Well, that was supposed to be C instead of C++, as I already used the cpp-tag earlier in my post and wanted to list some different examples. However, I must admit, I didn't check it with the compiler as I only wanted to test, if it would be formatted in this forum. I don't use C normally. But if I just replace "iostream.h" with "cstdio" it compiles fine. (Otherwise the compiler complains, that I'm using out-of-date headers.)
Nevertheless, thank you.

Generally pointers and references do similar things. In C+ it is considered preferable to use references if possible in large part because it is much much harder (but not impossible) to create an invalid reference than it is to create an invalid pointer.
That's interesting, as whenever I've seen a C++-Program (even in part) or heard about one, they've nearly always used pointers more than references. (As far as I can remember that is.)
Do these people just have a C background and don't "know better"? Or to reformulate that question: Is "Prefer references!" the opinion of most (good) developers?

1 important difference is that references must be initialised when the are declared where as pointers do not have to be. [...] It is quite a lot harder to go wrong with a reference than a pointer.
Makes sense. What advantages do pointers have then? I'm guessing, that Pointer-Arithmethics can't be used in any (reasonable) way with references, can they?

The code tags have changed, the previous code was buggy and holding up site development so it was removed. This is temporary and it will change again so keep putting in the language markers they may be used again someday.
Thanks, that's good to know. I'll continue using them. I must say, I preferred coloured and formatted code. :-)

Greetings,
Nepomuk
Jun 16 '08 #4
Banfa
9,065 Expert Mod 8TB
That's interesting, as whenever I've seen a C++-Program (even in part) or heard about one, they've nearly always used pointers more than references. (As far as I can remember that is.)
Do these people just have a C background and don't "know better"? Or to reformulate that question: Is "Prefer references!" the opinion of most (good) developers?
I'm not sure but I do now that examples in books are often written in a different style to production code. Normally to make the example simpler and easier to understand. User of pointers may be because the author is coming from a C background or because the auther expects the readers to be coming from a C background or because pointers were introduced first with-in the book.

"Prefer references!" is common sense, using something that is more robust rather than something that is less robust is likely to make you code more robust.

Makes sense. What advantages do pointers have then? I'm guessing, that Pointer-Arithmethics can't be used in any (reasonable) way with references, can they?
Pointers have the advantage that you don't need to initialise them when you declare them. This feature is essential for constructs like linked lists, of course you should be using list, map and set STL objects in your code but they have to implement their functionality somehow.

As you point out pointer arithmetic doesn't work on references and for this reason you can not have an array of references but you can have an array of pointers (of course you should be using a vector anyway but it is still easier to create a vector of pointers than a vector of references).

This stems from 2 things. A pointer is an object in it's own right that contains the address of another object. A reference just is the other object, any operation you try on the reference is applied to the object in question.

Pointers are essential if you are going to allocate memory from the heap. They are the only type that hold an address so you will need one to hold the address so you can test to make sure the allocation worked and so you can free the memory when you are finished with it.


Both types have there uses, I tend to stick to the rule of using references for pass data in and out of functions rather than pointers because it cuts down on the need to "check the pointer is valid" at the start of each function. I use pointers in the situations that definately require a pointer rather than a reference.

And of course I would be remiss if I failed to mention that instead of using pointer you can achieve more robust code by using the Handle Design Pattern, article here.
Jun 17 '08 #5
Nepomuk
3,112 Expert 2GB
Wow Banfa, that's a very informative answer! :-) I'll have a look at that article some time soon, but I guess I'll stick with the basics first. Still got a lot to learn... ^^

Thanks a lot,
Nepomuk
Jun 17 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

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. ...
4
by: cppaddict | last post by:
I understand that there are a couple differences between reference variables and pointer: 1) reference variables *must* be initialized. 2) You cannot change what a reference variable refers...
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...
7
by: Erdal Mutlu | last post by:
Hi, I am trying to design a base class (interface) with two or more subclasses as follows: class A { .... virtual static A* getByName(const string x)=0 const; }
64
by: Zytan | last post by:
I know there are no pointers in C#, but if you do: a = b; and a and b are both arrays, they now both point to the same memory (changing one changes the other). So, it makes them seem like...
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...
13
by: Chris Carlen | last post by:
Hi: I have begun learning Python by experimenting with the code snippets here: http://hetland.org/writing/instant-python.html In the section on functions, Magnus Lie Hetland writes: ...
5
by: arnuld | last post by:
it works fine: /* C++ Primer - 4/e * * example from section 7.2.2, pointer-swap * STATEMENT * in a function call where parameters are pointers, we actually copy the pointers. * here in this...
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: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
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...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
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.