Why aren't all C++ variables pointers? Why use pointers at all? Why the different syntax?

I come from an Objective-C background. In Objective-C, just about everything is a pointer. I know a pointer points to a variable in memory.

Why is passing a pointer to a function more efficient than passing the object itself? Why doesn't C++ make everything a pointer by default? Why do we use a different operator to access a value stored in a pointer?
Passing a pointer is not always more efficient. For simple types like int it's often more efficient to pass by value because the size of an int is normally equal or smaller compared to a pointer, and if you use a pointer you would have to dereference the pointer to access the value which adds some overhead.

Dynamic allocations using new usually has some overhead, both in terms of speed and memory usage. It also means things will likely be more spread out in memory (=less cache friendly) which could have a negative impact on performance (if a cache miss happens).

In C and C++ we are not forced to sacrifice performance just to make the language more secure/easy to use/whatever, unlike so many other languages. It means more responsibility to know what we are doing but it also means we can write very efficient code when needed.
Why doesn't C++ make everything a pointer by default?

If you ever did some microprocesser programming you would realize that the size of the program is very limited...
if you only use the heap (pointers) and dynamically allocate memory you have no Idea how big the program could become, if you only use the stack (no pointers) the compiler knows exactly how much space the data will take.

Furthermore you don't have to reallocate memory every time which also makes it a little bit more efficient.

Why do we use a different operator to access a value stored in a pointer?
This I don't even know after 3 years of doing C/C++...
but there are some cases where it is really useful...

if you know the standard memory-managing pointer classes you'd realise that the operator-> just returns a pointer to the object it stores, in addition to that it has some Methods...

So with a dot(.) you can access all public stuff in the std::unique_ptr object and with an arrow(->) you can access all public stuff in the object contained by it.

Why is passing a pointer to a function more efficient than passing the object itself?
because you don't have to copy the whole object.
imagine you have an object with an int array of 1000x1000 fields

If you pass by value, all those fields have to be copied, if you pass by reference/pointer you don't need to copy them.
Last edited on
Topic archived. No new replies allowed.