Size of empty class

http://www.cplusplus.com/forum/beginner/103745/

I was reading this post and the end of discussion "vlad from moscow" said that an empty class can have any size. When I performed it practically, I found that the size of an object of empty class is always 1 byte. What " vlad from moscow" said and this one byte size are puzzling me. Cab anyone explain?
Last edited on
> "vlad from moscow" said that an empty class can have any size.

A base class sub-object may have a size of zero.
Every other object (other than a bit-field) occupies some integral number of bytes - ie. has a size of 1, 2, 3 ... N.

1
2
3
4
5
struct A {} ; // empty  

A a1, a2 ; // a1 and a2 must have different, distinct addresses. 

A array[5] ; // each element of the array must have a unique address of its own 


sizeof(A) is typically one, but in theory, it may be more.

In theory, there is no difference between theory and practice. In practice, there is. - unknown
(often attributed to Yogi Berra)

Thanks for the reply but there's one thing that I did'nt get.

A base class sub-object may have a size of zero.

What exactly do you mean by a "sub-object"?
Last edited on
An object of a derived class type will contain anonymous (unnamed) sub-objects of each base class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main()
{
    struct A { int i = 0; } ;
    std::cout << "sizeof(A): " << sizeof(A) << '\n' ; // sizeof(A) == sizeof(int) == 4 (in this implementation)
    
    struct B : A { int j = 0; } ;
    std::cout << "sizeof(B): " << sizeof(B) << '\n' ; // sizeof(B) == sizeof(A) + sizeof(int) == 8
    std::cout << "sizeof(B::i): " << sizeof(B::i) << '\n' ; // sizeof(int) == 4
    std::cout << "sizeof(B::A): " << sizeof(B::A) << '\n' ; // sizeof(A) == 4
    
    B b ; // derived class object
    B& rb = b ; // reference to derived class object
    A& ra = b ; // reference to unnamed base class object contained in b
}

http://rextester.com/PHUF5673

However, if the base class is empty, the C++ standard permits an implementation to apply Empty Base Class Optimization (EBCO) aka Empty Base Optimization (EBO).
The details: http://en.cppreference.com/w/cpp/language/ebo
Thanks JLBorges, that was a great help. :)
Topic archived. No new replies allowed.