tags:

views:

102

answers:

2

I have a method that takes an object as an argument.

Both the caller and argument have the same members (they are instances of the same class).

In the method, particular members are compared and then, based on this comparison, one member of the argument object needs to be manipulated :

class Object {

   // members

public: 

someMethod (object other) {

   int result;
   member1 - other.member1 = result;
   other.member2 = other.member2 - result;

}

The only thing is that it doesn't actually change other.member2 out of this scope, and the change needs to be permanent.

So yes, sorry: I need advice on pointers... I have looked online and in books, but I can't get it working. I figure one of you will look at this and know the answer in about 30 seconds. I have RFTM and am at a stupid loss. I am not encouraging.

Thanks everyone!

+4  A: 

You are passing a copy of other to the someMethod function. Try passing a reference instead:

someMethod(object &other) { ...

When you pass a copy, your change to other.member2 changes only the copy and not the original object. Passing a reference, however, makes the other parameter refer to the original object passed in to the call to someMethod(obj).

Greg Hewgill
As a side note: passing complex objects as copies is expensive. Therefore even if the object is not changed inside the method, it is often preferable, to pass it as const reference. This avoids the copy and gives the caller a guarantee that the object isn't changed.
Gnafoo
+8  A: 

This is because you are passing by value (which equates to passing a copy. Think of it as making somebody a photocopy of a document and then asking them to make changes, you still have the original so the changes they make won't be reflected in your copy when you get it back. But, if you tell them where your copy is located, they can go and make changes to it that you will see the next time you go to access it). You need to pass either a reference to the object with

Object& object

or a pointer to the object

Object * object

Check out this page for a discussion of the differences.

Chris Thompson
Thank you so much! I really appreciate it. That is exactly what I was looking for!
Alec Sloman