As the question says, can someone explain the behavior below
class X{
public:
int *p;
void *q;
void goo(int v);
};
void X::goo(int v){
p = &v;
q = &v;
}
X foo(int v){
X x;
x.p = &v;
x.q = &v;
return x;
}
int main(int argc, char const *argv[])
{
X x = foo(10);
cout << *x.p << " " << *(int *)x.q << endl;
x.goo(3);
cout << *x.p << " " << *(int *)x.q << endl;
return 0;
}
OUTPUT
10 0
3 32764
The void pointer behavior is that of what is expected when the variables
are passed by reference...
class X{
public:
int *p;
void *q;
void goo(int &v);
};
void X::goo(int &v){
p = &v;
q = &v;
}
X foo(int &v){
X x;
x.p = &v;
x.q = &v;
return x;
}
int main(int argc, char const *argv[])
{
int a = 10;
X x = foo(a);
cout << *x.p << " " << *(int *)x.q << endl;
int b = 3;
x.goo(b);
cout << *x.p << " " << *(int *)x.q << endl;
return 0;
}
OUTPUT
10 10
3 3
Why in the first case, the behavior differs between void and int pointer. I think what I am lacking is a proper understanding of void pointer in c/c++. Can someone explain this?