Victor Schinaider
Victor Schinaider

Reputation: 1

C++ <type>*& in class function or struct error

Here is a part of my code:

class Node{
   public:
   Node* parent;
   Node* left;
   Node* right;
   int key;
};

(...)

/*
* Ps.: v1 is parent of v2!
* and assume that v1->parent is NULL
*/
void somefunction(Node*& v1,Node*& v2){
    (...)
    v2->parent = v1->parent; // The problem is here, more details below
    (...)
}

The problem is when I call v2->parent, because of the <type>*& in the argument of somefunction(), the compiler interprets that v2->parent is equal v1 (who is v2's father), and it modifies v1 to NULL, but I just want modify v2->parent value and not v1.

PS.: I need to use <type>*& in some parts below my code, I can't just modify the argument type.

Upvotes: 0

Views: 65

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110698

Seems like you're probably calling the function like this:

somefunction(v2->parent, v2);

That means that v2->parent inside the function is precisely the same object as v1 inside the function. When you set v2->parent to v1->parent (which is NULL), you are modifying v1 also.

You say you can't modify the argument types, but I suggest that you do. Having a reference to a pointer is a pretty bad sign. It seems like your code needs a redesign.

The alternative is that you copy v2->parent before you pass it to the function:

Node* v1 = v2->parent;
somefunction(v1, v2);

Now the v1 inside the function is this copy of v2->parent and won't modify the original.

Upvotes: 3

Related Questions