1. Empty class size
class A{};
Copy the code
The size of the empty class is 1. Each object has a unique address in memory space, and if size is 0 there is no way to allocate the address. So it’s going to give it the size of 1 byte. If it’s all zero and there are multiple instances of this class there’s no way to distinguish between multiple instances. C++ also specifies that sizeof should be greater than 0
2. Class with only functions (no virtual functions)
Functions don’t take up space so the size depends on other factors. Since the empty class is 1, this case is also 1.
class A{
void func(){}
};
Copy the code
Class with virtual functions
When virtual functions exist, extra space is required to store virtual table Pointers. On a 64-bit operating system, the virtual table size is 8 bytes. So 8 bytes in this case.
class A{
virtual void func(){}
};
Copy the code
4. Multiple inheritance and virtual functions exist
class A{ virtual void funcA(){} }; class B{ virtual void funB(){} }; Class C: public A, B{virtual void funcC(){}};Copy the code
During inheritance, different virtual tables are created for different parent classes. C inherits 2 so there are 2 virtual tables. Size = 8 + 8 = 16
5. Static variables exist
Static variables are shared by classes and therefore do not take up space. So it’s still 1 in this case.
class A{
static int num;
};
Copy the code
6. Common member variables exist. No memory alignment.
This is a simple case, a simple calculation of the stack. An int has 4 bytes, so 4 + 4 = 8. By the way, stick in the usual variable sizes.
Class A{int num1; int num2; };Copy the code
7. Common variables with memory alignment.
C++ defaults to byte alignment for faster access, which uses maximum granularity as the base unit of this class. For example, 8byte is used for both 4byte and 8byte
class A{
int int_num;
long long_num;
};
Copy the code
On 64-bit operating systems, this is 8 + 8 = 16. Even though int is 4, byte alignment makes it 8.
8. Virtual inheritance exists.
Virtual inheritance is to solve the diamond problem of multiple inheritance. But multiple inheritance is so lame that I didn’t study it.
9. Reference variables exist
class A{
public:
A(int& a) : v(a){ };
int& v;
};
Copy the code
The reference is essentially implemented using Pointers so this is also a pointer of size 8. Sizeof (a.v) is the sizeof the object to which the reference refers, which is 4.