what is the size of empty class in C++,java?

前端 未结 8 2122
北恋
北恋 2020-12-03 17:35

What is the size of an empty class in C++ and Java? Why is it not zero? sizeof(); returns 1 in the case of C++.

8条回答
  •  囚心锁ツ
    2020-12-03 17:54

    Short Answer:

    The standard explicitly says that a class can not have zero size.

    Long Answer:

    Because each object needs to have a unique address (also defined in the standard) you can't really have zero sized objects.
    Imagine an array of zero sized objects. Because they have zero size they would all line up on the same address location. So it is easier to say that objects can not have zero size.

    Note:

    Even though an object has a non zero size, if it actually takes up zero room it does not need to increase the size of derived class:

    Example:

    #include 
    
    class A {};
    class B {};
    class C: public A, B {};
    
    int main()
    {
         std::cout << sizeof(A) << "\n";
         std::cout << sizeof(B) << "\n";
         std::cout << sizeof(C) << "\n";  // Result is not 3 as intuitively expected.
    }
    
    g++ ty.cpp
    ./a.out
    1
    1
    1
    

提交回复
热议问题