#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