Pointer

Hello,

I want to ask
When will we need to use pointer??
Actually what is the benefit of using pointer??
What make pointer different from the usual program we use??

Thanks..
you use a pointer to point
this may be used to establish relationships between objects
1
2
3
4
5
6
struct car{
   person *driver;
   void crash(){
      driver->die();
   }
};
Last edited on
they have a lot of uses but most of those are hidden by the STL.
What if you needed a special purpose graph or tree or other data structure that is not in the STL? You can get one online of course, but how did they write it? At some level someone needed a pointer to build it.

A lot of programs that have hooks also use C style pointers; I work with a tool daily that lets you build external functionality that it can call, and it wants to use a char* or other basic type *s for that.

you may need them for low level code, such as writing your objects to a binary file efficiently.


A lot of legacy code used them and you need to understand how to edit / read such code at times.

a small number of object oriented designs require them.

you can use them to get direct bytewise access to some things; for example to byte reverse (endian) a 64 bit int. (bad example maybe, there are other ways to do that one, but sometimes you need a specific byte out of something).
You know how your program has variables to store the data? Sometimes you don't know how much data you'll have - think of a program that reads a bunch of numbers from a file. Will the file contain 5 numbers or 5,000? Without knowing, how will you store them?

To solve this problem, C++ lets you create objects at runtime. To access these objects, you use a pointer variable. Sometimes the object created contains pointer itself, so you can create an object that points to a created object that points to another created object etc.

This "creating an object" is generally referred to as "dynamic memory."
As others have noted, modern C++ includes plenty of (better) alternatives to using raw pointers, for most of the reasons we used to use them for, so you should rarely have to use them.

See my answer to the same question in another thread, for some of those reasons:

http://www.cplusplus.com/forum/general/105593/

pointers and their power don't really make sense until you understand the stackframe and function calls

Even then, references are more pervasive in C++ I think
Topic archived. No new replies allowed.