suppose that we have this simple class
Code:
class foo{
private:
struct node {
int x,y;
struct node *other; //pointer to another struct node
};
void change(struct node*);
struct node *root; //first node
public:
foo();
void change(); //changes values of some node
void add(int value); //add new value for both x and y, x=y=value
void show(); //show values
};
and here is the cpp file
Code:
#include "foo.h"
#include <iostream>
using namespace std;
foo::foo(){
root = NULL;
}
void foo::add(int z){
struct node *newnode = new node;
newnode->x = z;
newnode->y = z;
root = newnode;
struct node *othernode = new node; //create a new node and link it to root
othernode->x = 9;
othernode->y = 9;
root->other = othernode;
}
void foo::show(){
cout<<root->other->x<<endl;
}
void foo::change(struct node *ptr){ //ptr = node to change
ptr->other = NULL;
}
void foo::change(){
struct node *n = root;
change(n);
}
so basically we have a root which has a pointer to other node, and the other node has initial values of 9, then if I call the change() method for n = root and try to change the root->other to be NULL, it will change it.
but I don't get why this is happening, I pass the pointer by value not by reference to the change method so why exactly does it change the pointer value of root->other to be NULL?
would this thing work if I didn't have a class but did this inside a main.cpp file?
for example here
Code:
#include <iostream>
using namespace std;
void change(int *y){
y = NULL;
}
int main(void){
int z=10,*y=&z;
change(y);
cout<<y;
cin.get();
return 0;
}
the y remains the same..
thank you in advance
EDIT: I edited the whole thing... if you can please explain me, I would appreciate it