sizeof: Empty class or empty structure body

Source: Internet
Author: User
Tags object model

A child Boots the day before yesterday to the ideal international company interview, came back in the dormitory discussed such a question:

VC + +, there is an empty class, did not declare any member variables or functions, I would like to ask this empty class accounted for how large byte space?

A, 0 B, 1 C, 4 D, 8

The 32bit and 64bit machines were considered, and the pointer address was int, 32bit accounted for 4 bytes or 64bit was 8 bytes, so C and D were selected.

After thinking again, this does not operate the pointer, also does not need the memory alignment (depending on VC + + compiler will automatically alignment optimization), excluding the C and D, selected a

At that time also considered the Houtie teacher translated the "Deep Exploration of C + + object Model", C + + inheritance and polymorphism in the compiler is how to distinguish between, so 0 bytes is not reliable

But it's not going to be a byte at all, so it's the first time to completely killed B.

The interview back, in VC6.0, VS2010, g++ (Linux 2.6.31-14) compiled, found that the results are: 1

First, I post the test code:

#include <iostream>     
using namespace std;

Empty class class
ClassA
{
};

Inherits the empty class class
Classb:public ClassA
{
};

Empty structure body
struct STRUCTC
{
};

Main function
int main (int argc, char **argv)
{
    cout<< "A:" <<sizeof (ClassA) <<endl;
    cout<< "B:" <<sizeof (CLASSB) <<endl;
    cout<< "C:" <<sizeof (STRUCTC) <<endl;

    return 0;
}

Then, compile on each compiler

The results were as follows:

VC6.0 (XP Professional sp2-32bit)

VS2010 (Win7 Ultimate Sp1-64bit)

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.