Struct&&class size of empty

Source: Internet
Author: User
Tags classe

#includeusing namespacestd; classClassA {}; classClassB {Private:    intb;  }; classClassC: PublicClassA {}; classCLASSD: PublicClassB {}; classClassE { Public:    intGetreturnvalue () {return 0;  }  }; structStructa {}; intMain () {cout<<"ClassA"<<sizeof(ClassA) <<Endl; cout<<"ClassB"<<sizeof(ClassB) <<Endl; cout<<"ClassC"<<sizeof(ClassC) <<Endl; cout<<"CLASSD"<<sizeof(CLASSD) <<Endl; cout<<"ClassE"<<sizeof(ClassE) <<Endl; cout<<"structa"<<sizeof(STRUCTA) <<Endl; }
1  41)41       1      

A class can be instantiated, and the compiler will need to allocate memory space to indicate the address of the class instance. By default, the compiler allocates a byte (for example, char, compiler-related) to mark a class instance that might initialize, while leaving the empty class with the least amount of space (that is, 1 bytes).

For structs and empty class size is 1 This problem, first of all this is a C + + problem, in C language, the size of the empty structure is 0 (of course, this is compiler-related). The empty and empty structures here refer to the absence of any members in the class or struct body.

In C + +, the size of the empty class and the empty struct is 1 (compiler-related), which is why? Why not 0?

This is because the C + + standard stipulates that "No object shall has the same address in memory as any other variable", that is, any different object cannot have the same memory address. If the empty class size is 0, if we declare an array of objects of this class, then each object in the array has the same address, which is obviously against the standard.

Struct&&class size of empty

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.