Schilcote Schilcote - 18 days ago 5
C++ Question

-> operator not allowed on statically allocated objects in C++?

I'm a self-taught programmer taking a formal college programming course for the first time. Today someone asked the instructor in a C++ class what the

->
operator does.

The instructor said something along the lines of "the arrow operator is the equivalent of the dot operator except for dynamically allocated objects. You can only use the dot operator on statically allocated objects [followed by an example of declaring variables at the beginning of a block], and you can only use the arrow operator on dynamically allocate objects you made with
new
."

C++ is absolutely not my area of expertise... but every other thing I've looked at said
a->b
is exactly equivalent to
*a.b
, and that it existed mainly for legacy reasons because variables worked differently in early versions of C++.

Is it true that
->
cannot be used on pointers to objects that are allocated on the stack, and that
.
cannot be used on dereferenced pointers to objects allocated on the heap?

Answer

Your instructor's answer is not correct, it generalizes for some usual basic cases but it also shows that he or she does not really have any experience in writing larger projects in C++. Here is why:

If you allocate objects on the stack, i.e. use the automatic memory of C++, you would usually do something like:

SomeClass object;
object.doSomething();

If you allocate the memory on the heap, it would usually look like this:

SomeClass* object = new SomeClass; // unique_ptrs are a better way but this might be easier to grab for now
object->doSomething();
delete object;

But you might also refer to object via a reference, so that . works again. And you might have a pointer that refers to your object that has been allocated on the stack or the heap, thus accessing with -> works.

All in all, . is used to access non-pointers and -> is used to access pointers. Also, there might be classes that have operator-> overloaded. Then, you can also access a non-pointer instance of a class with that operator.

Comments