I've read that a non-const member function of a class can only be called on non-const objects. My question is, why can a non-member function which takes a non-const pointer, be called with a const pointer? I tried this code:
int k = 10;
int x = 5;
void func(int *n) {
n = &k;
cout << *n<< ", x: " << x << endl;
}
int main()
{
int * const ptr=&x;
cout << *ptr << endl; //prints 5
cout <<"x:"<< x << endl; //prints x:5
//ptr = &k; //compiler error
cout << "ptr value (address): " << ptr << endl; //prints 001DC038
func(ptr); //prints 10, x: 5
cout << "x:" << x << endl; //x: 5
cout << *ptr << endl; //5
cout << "ptr value (address): " << ptr; //prints 001DC038
}
I'm not sure I understood it right, but the line func(ptr)
calls func()
with ptr's value which is &x, and n=&k
is supposed to change x's address to k's address? but it prints different values for *n
and x
, so what exactly was sent to func()
?
Is the syntax wrong?