Question about pointer

Why do we use pointers when we can just directly set the value of a variable to another like in the 2nd code? Just started getting into pointers and that was the first question that popped into my mind. If someone could give me an example, that would help a lot. I'm a beginner at c++ so simple explanations would be the best.

1
2
3
4
5
6
7
8
9
10
11

        int x = 25;
	int* p = &x;

	cout << *p;

vs

        int x = 25;
	int p = x;
        cout << x;
It's true that the examples you've seen for how to use pointers are unrealistic, and in practice there isn't really any reason to use them that way.

The "why do we use pointers" topic is difficult because most instances of pointers either rely on other concepts (like polymorphism) or are non-trivial examples (reference counting). There's no simple example I could give you that would be realistic or easy to understand for a beginner.

If you want to learn more about why pointers are useful, look into inheritance and polymorphism. You need to have a pointer when using polymorphism because otherwise you suffer from "object slicing". None of this makes any sense to you yet, I'm sure... but read up on it if you're curious. Or.... just wait until you get to those topics before wondering why pointers are useful.
Thank you disch. I guess for now ill just go along with the unrealistic use of pointers. Hopefully, ill be able to get to the point where i start using pointers in a practical manner.
This example should give u a hint why to use pointers!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

int x = 25;
int* p = &x;
x++;

cout << "p: " << *p << "x: " << x;

vs

int x = 25;
int p = x;
x++;

cout << "p: " << p << "x: " << x;
Last edited on
Another reason pointers are useful is for APIs that were not written for C++. Keep in mind that C++ is backward compatible with C, and in C pointers are important for passing thing around. C does not have pass by reference, so if you want to change the value of an object in the caller, you have to pass using a pointer.
> Why do we use pointers when we can just directly set the value of a variable
the value of the pointer may change at run-time, however its meaning remains (e.g., first, minimum)
1
2
3
4
5
6
7
class car{
   person *driver
public:
   void crash(){
      driver->die();
   }
};
¿who do you kill?
Topic archived. No new replies allowed.