some questions about pointer to struct

Hi, I am having trouble understanding the following code on page 318 in Thinking in C++:

#include <iostream>
using namespace std;

union U {
private:
int i;
float f;
public:
U(int a);
U(float b);
~U();
int read_int();
float read_float();
};
U::U(int a) {i=a;}
U::U(float b) {f=b;}
U::~U(){cout<<"U:~U()\n";}
int U::read_int(){return i;}
float U::read_float(){return f;}

int main(){
U X(12), Y(1.9F);
cout<<sizeof(X)<<endl; #4 ok
cout<<X.read_int()<<endl; #12 ok
cout<<Y.read_float()<<endl; #1.9 ok
cout<<X.read_float()<<endl; #1.68156e-044 don't know...
cout<<&X<<endl; # 0x22ff20 ok
int *p=(int*)0x22ff20; # ok
cout<<*p<<endl; # 12 ok, but since i is private, now p can acess it?
*p=15; #ok
cout<<X.read_int()<<endl; #15, why can p even change its value?
cout<<X.read_float()<<endl; # 2.10195e-044 don't know..

system("PAUSE");
return 0;
}


Thank you so much everyone!
hehe, and I am having trouble to understand your code. Try doing this next time you post a code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;

union U {
private:
int i;
float f;
public:
U(int a);
U(float b);
~U();
int read_int();
float read_float();
};
U::U(int a) {i=a;}
U::U(float b) {f=b;}
U::~U(){cout<<"U:~U()\n";}
int U::read_int(){return i;}
float U::read_float(){return f;}

int main(){
U X(12), Y(1.9F);
cout<<sizeof(X)<<endl; #4 ok
cout<<X.read_int()<<endl; #12 ok
cout<<Y.read_float()<<endl; #1.9 ok
cout<<X.read_float()<<endl; #1.68156e-044 don't know...
cout<<&X<<endl; # 0x22ff20 ok
int *p=(int*)0x22ff20; # ok
cout<<*p<<endl; # 12 ok, but since i is private, now p can acess it?
*p=15; #ok
cout<<X.read_int()<<endl; #15, why can p even change its value?
cout<<X.read_float()<<endl; # 2.10195e-044 don't know..

system("PAUSE");
return 0;
}
What is the problem??Can you please be more specific in your question??

When you make the variable X of the union ,you call the constructor that assigns the value to the integer i of the union.The float variable f is assigned a dummy value proportional to the value of the int variable i.
so when i=12,f=1.68156e-044

in the case of the pointer p,you assign it the address of the variable X of the union,so its value becomes the value that you called the constructor with.i.e. *p=12.

In the very next statement you assign the value*p=15 thereby assigning 15, to the variable i and a proportional value to the variable f=2.10195e-044.


Topic archived. No new replies allowed.