Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating data members (C++)

Tags:

c++

pointers

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!

like image 551
Alec Sloman Avatar asked Dec 16 '22 23:12

Alec Sloman


2 Answers

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.

like image 186
Chris Thompson Avatar answered Dec 19 '22 14:12

Chris Thompson


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).

like image 28
Greg Hewgill Avatar answered Dec 19 '22 12:12

Greg Hewgill