I have five classes here, class A B C I can explain the size of them.
class D I expect the result is 12 bytes, but the output is 16 bytes, I found the reason is that after adding the virtual function, the alignment will become 8 bytes,
So I created the Test class again, according to the above reasoning, my expected result is 16 bytes, but after running, the result is 12 bytes,
Should not the Test class is also 8 bytes alignment, and the result should be 16 bytes? Or what causes the class to perform 8 bytes alignment?
Code:
#include <iostream>
using namespace std;
class A
{
//empty
};
class B
{
int a = 123;
};
class C
{
public:
void print(){
cout << "C" << endl;
}
private:
int i = 123;
};
class D
{
public:
virtual void print(){
std::cout << "D" << std::endl;
}
virtual int d(){
return 0;
}
void add(){
std::cout << "D add" << std::endl;
}
private:
int i;
};
class Test
{
private:
int i;
int j;
int l;
};
int main(){
cout << sizeof(A) << endl;//1 byte:avoid null pointer
cout << sizeof(B) << endl;//4 bytes:one int
cout << sizeof(C) << endl;//4 bytes:one int
cout << sizeof(D) << endl;//16 bytes(using 12byte):one int one pointer and 8 alignment
cout << sizeof(Test) << endl;//12 bytes:Why not 16 bytes?
return 0;
}
CodePudding user response:
class D I expect the result is 12 bytes, but the output is 16 bytes
Your expectation is misguided.
I found the reason is that after adding the virtual function, the alignment will become 8 bytes,
That's the reason. 12 is not aligned to 8 bytes. 16 is.
So I created the Test class again, according to the above reasoning, my expected result is 16 bytes, but after running, the result is 12 bytes,
You didn't add virtual functions to Test
, so your expectation is wrong.
Should not the Test class is also 8 bytes alignment,
There's no reason to expect that.
Or what causes the class to perform 8 bytes alignment?
In this case, it was caused by having a virtual member function. In other cases it can also be caused by having a sub object with alignment of 8.