Space size of empty class, virtual function class, and virtual inheritance class

Source: Internet
Author: User

# Include <iostream>
Using namespace STD;
Class A // A is an empty class. The compiler will mark this class with a char type and the size is 1.
{

};
Class B: public a // B inherits a, but it is also an empty class with the size of 1
{

};
Class C: Virtual
Public A // during virtual inheritance, the compiler inserts a pointer to the parent class with a size of 4
{

};
Class D // The size is 4
{
Public:
Int;
Static int B; // static variables are stored in the static storage area.
};
Class E // print function does not occupy memory space, size is 4
{
Public:
Void print () {cout <"E" <Endl ;}
PRIVATE:
Int;
};
Class F // virtual functions occupy the memory of a pointer. The system needs to use this pointer to maintain the virtual function table. The size is 8.
{
Public:
Virtual void print () {cout <"F" <Endl ;}
PRIVATE:
Int;
};
Class G: Public f // The memory size of one more virtual function remains unchanged. It can be seen that a class has only one virtual function pointer. The size is 8.
{
Public:
Virtual void print () {cout <"G" <Endl ;}
Virtual void print2 () {cout <"G2" <Endl ;}
};
Int main ()
{
A;
B;
C;
D;
E;
F;
G;
Cout <sizeof (a) <"" <sizeof (a) <Endl; // 1
Cout <sizeof (B) <"" <sizeof (B) <Endl; // 1
Cout <sizeof (c) <"" <sizeof (c) <Endl; // 4 4
Cout <sizeof (d) <"" <sizeof (d) <Endl; // 4 4
Cout <sizeof (e) <"" <sizeof (e) <Endl; // 4 4
Cout <sizeof (f) <"" <sizeof (f) <Endl; // 8
Cout <sizeof (g) <"" <sizeof (g) <Endl; // 8

Return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.