Class A
{
};
sizeof (A) does not get 0 but 1, because when we declare the type instance, it must occupy a certain amount of space in memory, otherwise it will not be able to use these instances.
The amount of memory occupied by the compiler is determined by the result of my VS2008.
Class A
{
Char A;
};
The result of this sizeof is 1, not 4, and there is no memory alignment (VS2008) in the case of only one char member.
Class A
{
Char A;
Char b;
};
Get 2 (not specifically stating that other compilers are VS2008).
Class A
{
int A;
Char b;
};
Get 8.
Class A
{
char c;
int A;
Char b;
};
Get 12.
Class A
{
int A;
Char b;
char c;
};
Get 8.
The above example already shows exactly what's going on in memory alignment ...
Here's what happens when you add a virtual function:
Class A
{
virtual void fun ();
};
Get 4 because a virtual pointer is included, and the generic compiler defaults to putting the virtual pointer to the end.
Class A
{
Char A;
virtual void fun ();
};
Get 8;
Class A
{
Char A;
virtual void fun ();
Char b;
};
This is still 8.
Class A
{
int D;
Char A;
virtual void fun ();
Char b;
};
Get 12.
Class A
{
Char b;
int D;
Char A;
virtual void fun ();
};
Get 16.
Take a look at what might happen in inheritance, Lippman in the Deep exploration of the C + + object model for a number of scenarios,
Especially when it comes to virtual inheritance and multiple inheritance, I have little experience, and I haven't seen it yet. Or not apply to be slowly abandoned it.
The content involved in this is too complex, and compiler-related, different compiler strategy, the future has the opportunity to summarize.
Class A
{
Char b;
int D;
virtual void fun ();
Char A;
};
Class B:public A
{
Char h;
virtual void test ();
};
int _tmain (int argc, _tchar* argv[])
{
Cout<<sizeof (A) <<endl;
Cout<<sizeof (B) <<endl;
}
Get 16,20
Class A
{
int D;
virtual void fun ();
Char A;
Char b;
};
Class B:public A
{
Char h;
virtual void test ();
};
int _tmain (int argc, _tchar* argv[])
{
Cout<<sizeof (A) <<endl;
Cout<<sizeof (B) <<endl;
GetChar ();
return 0;
}
Get or 12, 16.
That is, the inherited parent class is fully saved, including the virtual pointer of the parent class.
It does not try all kinds of possible situations, perhaps you will have accidentally found, can share, sleep!
C + + memory alignment