Pointer vs non-pointer

1
2
3
struct product {
int weight;
};

Is there a difference between using a pointer or non-pointer for the following case?

1
2
product apple;
apple.weight = 0; //non-pointer 

VS.
1
2
3
4
product apple;
product *approduct
aproduct &apple;
aproduct -> weight = 0;
Is there a difference between using a pointer or non-pointer for the following case?
You need to initialize the pointer/reference.

Note that you can access non pointer obects only within their scope
You can also access pointer objects only within their scope.
Besides initializing the pointer, it is pretty much the same? So basically only memory used.

@cider777 and cire
So you can access pointer and non-pointer objects?
1
2
3
struct product {
int wieght;
};


1
2
product apple; // creates a product named apple
apple.weight = 0;


1
2
product* apple = new product; // creates a product.  Apple now points to that product
apple->weight = 0;


The two bits of code are effectively the same in that they both create an apple and set the weight to 0. Obviously the pointer syntax is a little more complicated to use. Even worse, at the end of the apple's scope, the object will still exist in memory unless manually deleted. That gives the potential for memory leaks. If you're fine with using pointers, then go with it, but unless you HAVE to use them, try to avoid them. It will make your code simpler and safer.
Last edited on
closed account (zb0S216C)
There's little difference between the two code segments. The first code segment displays direct access of "apple"'s data members whereas the second code segment displays indirect access of "apple"'s data members.

In addition, the second code segment incurs a memory overhead, but that's another subject in itself.

Wazzak
Last edited on
@Stewbond
@Framework

Thanks for the answers.
Topic archived. No new replies allowed.