Sign in to follow this  
Oni Sephiroth

pointers, objects and classes (C++)

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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 target
if (selection == 1) target = ptr1;
else target = ptr2;


// This part of the code is seperated
target->value = target->value * target->value;

Share this post


Link to post
Share on other sites
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;

Share this post


Link to post
Share on other sites
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....

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this