Why, in the following code, is sizeof(X) == 4 and sizeof(Y) == 8?
Moreover, in the class X, why do the member functions not take any memory space?
class X {
int i;
public:
X() { i = 0; }
void set(int ii) { i = ii; }
int read() const { return i; }
int permute() { return i = i * 47; }
};
class Y : public X {
int i; // Different from X's i
public:
Y() { i = 0; }
int change() {
i = permute(); // Different name call
return i;
}
void set(int ii) {
i = ii;
X::set(ii); // Same-name function call
}
};
cout << "sizeof(X) = " << sizeof(X) << endl;
cout << "sizeof(Y) = " << sizeof(Y) << endl;
Objects of class
Yhave two integer members; objects of classXhave one. Your comments express the fact thatY‘siis different fromX‘si, so it looks like you already knew the answer.See http://codepad.org/PZsiyFIk for an example of how an object of class
Yactually has twoimembers.Code repeated here:
Outputs
There is only one object in
maincalledy. Note thatymust have twoifields for the output to make sense.