473,792 Members | 2,807 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Understanding of Pointers and References

Nepomuk
3,112 Recognized Expert Specialist
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.2660078828054 98, -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 1875
oler1s
671 Recognized Expert Contributor
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 Recognized Expert Moderator Expert
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 Recognized Expert Specialist
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 Recognized Expert Moderator Expert
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 Recognized Expert Specialist
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
14040
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. WD
4
4959
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 to. My question is: In what situations is it better to use a reference variable over a pointer? Also, are there other differences besides the ones I listed above?
458
21483
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 simply aren't smart enough to understand C++? This is not merely a whimsical hypothesis. Given my experience with Java programmers --- the code they write and the conversations they have --- Occam's Razor points to this explanation. For example,...
7
1517
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
3440
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 pointers. Can someone please explain why? thanks. Zytan
9
2474
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 deal with references which are local variables. But references can also be function arguments (in fact they are more useful this way) in which case it has to have the in-memory representation.
13
3026
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: -------------------------------------------------------------------- For those of you who understand it: When you pass a parameter to a
5
1887
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 example we are using the original pointers. *
19
1993
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 references. Yet, in an interview, he laments the overuse of pointers and such in code. It seems contradictory to me. Why should we not use references instead of pointers? Can someone give me an idea of best practices in this respect? regards,...
0
9670
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
9518
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
10211
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
9033
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...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6776
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();...
1
4111
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
2
3719
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2917
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.