I know the difference between the points-to (->) and dot (.) operator but I don’t see why the need for the two arrises? Isn’t it always just as easy not to use pointers and just use the dot operator? From http://www.programcreek.com/2011/01/an-example-of-c-dot-and-arrow-usage/
#include <iostream>
using namespace std;
class Car
{
public:
int number;
void Create()
{
cout << "Car created, number is: " << number << "\n" ;
}
};
int main() {
Car x;
// declares x to be a Car object value,
// initialized using the default constructor
// this very different with Java syntax Car x = new Car();
x.number = 123;
x.Create();
Car *y; // declare y as a pointer which points to a Car object
y = &x; // assign x's address to the pointer y
(*y).Create(); // *y is object
y->Create();
y->number = 456; // this is equal to (*y).number = 456;
y->Create();
}
Why ever bother using pointers? Just create Y as X was, it would work the same. If you say you need pointers for dynamically alocated memory, then why bother having the dot operator?
I think you’re mixing two separate concerns.
First, the
->operator is unnecessary, yes.x->yis equivalent to(*x).y, but the->operator is easier to type, so it’s basically just a convenience.The second part is whether to use pointers at all.
And you’re right, often you shouldn’t. By default, just create your objects then and there, and refer to them direclty:
but pointers are still necessary for a lot of cases. Objects need to be able to reference other objects. A reference can do that, but it can’t be reseated. Once it is initialized, it will always point to the same object.
A pointer can be updated to point to a different object.
Linked lists, tree data structures and countless other things depend on objects being able to point to other objects.
So yes, we need pointers. But we don’t need the
->operator. We just use it because it’s convenient.