The size of "program design" C and C + + hollow structure and empty class

Source: Internet
Author: User

Today encountered a pen question, asked what is the size of the C + + empty class is what, with the program tested a bit.

#include <iostream>using namespace Std;class ClassA {};//struct STRUCTA {////};int main () {  cout << "C LassA "<< sizeof (ClassA) << Endl;}

The output result is 1;



Expands on how space in C and C + + is occupied by an empty class followed by an empty struct.

In C + +, each time a class or struct is defined, the compiler assigns it at least 1 bytes of memory by default, guaranteeing that it has its corresponding location in memory , so that once the class or struct is instantiated, it will not cause an error because the memory cannot be found.

#include <iostream>using namespace Std;class ClassA {};struct structa {};int main () {ClassA a;struct structa b;cout << "ClassA" << sizeof (ClassA) << endl;cout << "a" << sizeof (a) << endl;cout << ; "Structa" << sizeof (STRUCTA) << endl;cout << "B" << sizeof (b) << Endl;}

Results:



Obviously, in C + +, the existence of an empty class and an empty struct is allowed, and both allow instantiation (no compilation errors).


Instead. There are no classes in C, only structs, and when you define a struct, the C language does not intelligently allocate memory for it, so the empty struct does not exist in C.

(VC6.0 is compiled but this is related to compilers)




This article was written by Cout_sev.

If there is a mistake, please correct

Reprint Please specify source: http://blog.csdn.net/cout_sev/

Thank you for your cooperation!



The size of "program design" C and C + + hollow structure and empty class

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.