Brendan Lesniak
Brendan Lesniak

Reputation: 2311

What's the real ”point” of pointers?

I've programmed in Java quite a bit, and have dabbled in C++ before. I've read about pointers in various C++ books, and done the various examples in books.

I understand the pointer basics, but one thing has never been clear to me. What is the real world application of pointers? I mean, in what situation would using pointers be more beneficial than just passing by reference (like in Java?)

Upvotes: 1

Views: 2117

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564413

I mean, in what situation would using pointers be more beneficial than just passing by reference (like in Java?)

References in Java and many other languages are basically an abstraction on top of pointers. In C (not C++), there was no way to "pass by reference" like you can in C++ with references, as that abstraction didn't exist, so this was never a possibility. C++ added references as a new abstraction.

With C++, you can pass by reference, and that's often preferred. However, the actual dynamic memory allocation will still, at some level, work with pointers.

That being said, there are some things you can do in C++ with pointers which can lead to nice efficiencies. Knowing about memory and what's stored there allows you to directly manipulate that data without the overhead of the abstractions you get in some languages. This isn't "safe" (it's easy to do something dangerous and bad) - but it is often useful. (It's useful enough that some languages, like C#, allow you to do this as well, though they require you to explicitly mark that code as "unsafe" in order to allow it.)

That being said, pointers are typically abstracted in C++. Smart Pointers provide a lot of the same benefits without the side effects and dangers of working with "raw" pointers...

Upvotes: 9

Florin Stingaciu
Florin Stingaciu

Reputation: 8285

The main difference (to me at least) is the time when you pick one or the other. I think if you need to do pointer arithmetic or assign the NULL value to it, then use pointers otherwise just stick to references; they do the job.

Upvotes: 0

Related Questions