I am trying to fully understand how class sizes are determined in C++ so I can keep this in mind when designing data structures. I have some classes that I have created for testing but seem to struggle on some of the sizes, perhaps due to not knowing the order in which the sizes are added together.
Consider the following on a 64-bit compilation
class A {
public:
virtual void work() {}
private:
float a;
float b;
};
class B : A {
private:
float b1;
};
class C : A {
private:
float c1;
};
class D : C {
private:
float d1;
};
struct DCA {
float d1;
float c1;
float a;
float b;
void* function;
};
int main()
{
std::cout << sizeof(A) << std::endl;//16
std::cout << sizeof(B) << std::endl;//24
std::cout << sizeof(C) << std::endl;//24
std::cout << sizeof(D) << std::endl;//32
std::cout << sizeof(DCA) << std::endl;//24;
}
Now I understand that a pointer is created when using a virtual function which on 64-bit adds 8 bytes.
Is this pointer only for the class that has the virtual function, or the derived class also.
What is the order in which I would calculate the size. If I was calculating the size of D, would I start by calculating the size of A, then C, then D?
struct
DCA
has the same variables as class D, however its size is 24 and the size of classD
is 32. I would have expectedD
to be 24 also as I'm counting the floats first which is 16 bytes, and then 8 bytes for the pointer. 24 is divisible by 8 which is 8 byte aligned.
Can someone attempt to answer these questions and tell me where I am going wrong with my logic?
The duplicate question does not address virtual keyword, inheritance or order of calculations. It also doesn't mention whether or not there is a standard specific byte alignment.