vendredi 6 novembre 2020

C++ calling method by following a pointer changes the pointer, when it should not [closed]

I am quite new to C++ and I have the code as bellow:

Line 1: TreeNode<T>* node = ... //points to sth
Line 2: node -> method (new TreeNode<T>(item));
Line 3:
Line 4: void method(TreeNode* child){
Line 5:     cout << data << endl; // data stored in node
Line 6:     cout << child->data << endl; // data stored in child
Line 7: }

I always make sure that data in node and data in item/child are different. Now, the method works as it should almost all the time, but there are cases when it prints the same values when it should not. It seems that calling line 2 changes either variables in the pointer node or the pointer itself.

Why does it happen?

Aucun commentaire:

Enregistrer un commentaire