Thursday, September 20, 2007

Inside the c++ object model (3)

class X
{
};
class Y: public virtual X
{
};
class Z: public virtual X
{
};
class A: public Y, public Z
{
};

int main(int argc, char **argv)
{
printf("size X=%d\n", sizeof(X));
printf("size Y=%d\n", sizeof(Y));
printf("size Z=%d\n", sizeof(Z));
printf("size A=%d\n", sizeof(A));
return 0;
}

--
An empty class in practice is never empty. It has an associated size of 1 byte-a char member inserted by the compiler. This allows two objects of the class X a, b; (&a, &b) to be allocated unique address in memory.
An empty virtual base class is treated as being coincident with the beginning of the derived class object. It takes up no additional space.
A virtual base class suboject occurs only once in the derived class regardless of the number of times it occurs within the class inheritance.
1 4 4 8

Where should the vptr be placed within the class object? -- at the beginning of the class object.

Static date members are lifted out of their class and treated as each were declared as a global variable ( but with visibility limited to the scope of the class ).
The static member is not contained within a class object.

Point3d origin, *pt = &origin;
origin.x = 0.0;
pt->x = 0.0;

what is the significantly different when accessed through the object origin or the pointer pt? -- when the Point3d class is a derived class containing a virtual base class within its inheritance hierarchy and the member being accessed, such as x, is an inherited member of that virtual base class.
class Concrete{
public:
private:
int val;
char c1;
char c2;
char c3;
};

4 bytes for val, 1 byte each for c1,c2,c3 and 1 byte for the alignment, totally 8 bytes.
class Concrete{
public:
private:
int val;
char bit1;
};
class Concrete2{
public:
private:
char bit2;
};
class Concrete3{
public:
private:
char bit3;
};

Concrete3 size is 16 bytes.
Concrete2 *pc2;
Concrete1 *pc1_1, *p2_2;

Both pc1_1 and pc2_2 can address objects of either three classes.
pc1_1 = pc2;
*pc1_1 = *pc2_2; // trouble

derived class subobject is overridden, bit2 member now has an undefined value.

No comments:

Post a Comment