Empty class and empty struct size

Source: Internet
Author: User

// This is an empty test, only the test size

Class {};

Class B {};

Class C: Public {

Virtual void fun () = 0;

};

Class D: Public B, public C {};

// Cout <"sizeof (a)" <sizeof (a) <Endl;

// Cout <"sizeof (B)" <sizeof (B) <Endl;

// Cout <"sizeof (c)" <sizeof (c) <Endl;

// Cout <"sizeof (d)" <sizeof (d) <Endl;

// The output result of the program execution is:

//

// Sizeof (A) = 1

//

// Sizeof (B) = 1

//

// Sizeof (c) = 4

//

// Sizeof (d) = 8

/**

Why is this result? Beginners will be very upset, right? Class A and B are clearly empty classes, and their size should be 0. Why is the compiler output 1? This is the reason we just mentioned for instantiation (empty classes can also be instantiated). Each instance has a unique address in the memory. To achieve this, the compiler often implicitly adds a byte to an empty class, so that the empty class gets a unique address in the memory after instantiation. so the size of A and B is 1.

 

Class C is generated by Class A, which has a pure virtual function. Due to the virtual function, there is a pointer to the virtual function (vptr ), in the 32-bit system, the pointer size is 4 bytes, so the size of class C is 4.

 

The size of class D is even more confusing for beginners. Class D is derived from Class B and C. Its size should be the sum of 5 and why is it 8? This is because it is used to improve the access efficiency of the instance in the memory. the class size is usually adjusted to an integer multiple of the system. and take the nearest law, in which the nearest multiple is the size of the class, so the size of class D is 8 bytes.

 

Of course, the results may be different on different compilers, but this experiment tells us that beginners can be instantiated regardless of whether the class is empty or not (empty classes can also be instantiated ), each instance has a unique address.

*/

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.