Sample size analysis of C++ empty classes and classes without member variables

  • 2020-04-02 02:26:35
  • OfStack

The well-known C++ hollow class has a size of 1, but quite a few developers have a lot of confusion about the size of other classes that have no member variables other than empty classes.

Here we take the following code as an example:


#include
using namespace std;
class a {};
class b{};
class c :public a{
virtual void fun() = 0;
};
class d :public b, public c{};
int main()
{
cout << "sizeof(a)" << sizeof(a) << endl;
cout << "sizeof(b)" << sizeof(b) << endl;
cout << "sizeof(c)" << sizeof(c) << endl;
cout << "sizeof(d)" << sizeof(d) << endl;
getchar();
return 0;
}

The output result of program execution is:


sizeof(a)=1
sizeof(b)=1
sizeof(c)=4
sizeof(d)=8

Why does this happen ? Beginners will be puzzled by this, class a, class b is clearly empty, its size should be zero, why the compiler output is 1 ? This is why we just said instantiation (an empty class can also be instantiated), each instance has a unique address in memory, and to do that, Compilers often add a byte implicitly to an empty class, so that the empty class gets a unique address in memory after instantiation So the magnitude of a and b is 1.

While class c is derived from class a, it has a pure virtual function, because there are virtual functions, there is a pointer to the virtual function table (VPTR, there are multiple virtual functions still only one pointer), in A 32-bit system assigns a pointer size of four bytes, so you end up with a c class size of four .

The size of class d will make many beginners wonder, class d is derived from class b, c, its size should be the sum of the two 5, why is it 8 ? This is because in order to improve the efficiency of instance access in memory, there is data alignment in memory, so the size of the class is often adjusted to an integer multiple of 4 bytes. The nearest multiple in the larger direction is the size of the class, so the size of class d is 8 bytes (still 8 if d is derived from 3 empty classes and c).


Related articles: