pointers, objects and classes (C++)

Started by
3 comments, last by polymorphed 16 years, 1 month ago
Can someone tell me the benefits of using a pointer to access class data rather than creating an object? For example, how is...

someclass * pointer = new someclass;

pointer->blah += 5;
better than..

someclass object;

object.blah += 5;
I just don't see a difference. Unless there's more to it than just accessing the data.
Advertisement
Pointers (or references) can be used to refer to polymorphic classes and objects cannot.
Another big advantage is that you can just delete it when you're done with it.
When you create an object on the stack, it isn't removed until it goes out of scope.

And when you use pointers you create an abstraction, you can change which objects are being the target of the code, without affecting other parts of the code.
For example:

int selection = 1;someclass *ptr1, *ptr2, *target;ptr1 = new someclass;ptr2 = new someclass;ptr1->value = 42;ptr2->value = 0;// Set targetif (selection == 1) target = ptr1;else                target = ptr2;// This part of the code is seperatedtarget->value = target->value * target->value;
while (tired) DrinkCoffee();
Quote:Original post by polymorphed
*** Source Snippet Removed ***


someclass obj1, obj2;obj1.value = 0;obj2.value = 42;someclass &target = (selection == 1) ? obj1 : obj2;target.value = target.value * target.value;
Quote:Original post by ToohrVyk
Quote:Original post by polymorphed
*** Source Snippet Removed ***


someclass obj1, obj2;obj1.value = 0;obj2.value = 42;someclass &target = (selection == 1) ? obj1 : obj2;target.value = target.value * target.value;


But once you have initialized a reference you can't change it, but you can change a pointer as much as you'd like....
while (tired) DrinkCoffee();

This topic is closed to new replies.

Advertisement