+ 6
How counts the operator sizeof(type) the size of a class?
#include <iostream> class A { int i; char charVec[3]; public: const int& size() const { return sizeof(i) + sizeof(charVec); } }; class B { int i; char charVec[5]; public: const int& size() const { return sizeof(i) + sizeof(charVec); } }; int main() { A a; B b; std::cout << "The size of class A with using the operator sizeof: " <<sizeof(A) << std::endl; std::cout << "The correct size of class A: " << a.size() << std::endl; std::cout << "The size of class B with using the operator sizeof: " << sizeof(B) << std::endl; std::cout << "The correct size of class B: " << b.size()<< std::endl; std::cin.get(); std::cin.get(); return 0; }
4 Antworten
+ 5
sizeof takes the accumulated object sizes of each member variable.
For example the size of an
int is 4 bytes,
char is 1 byte,
short is 2 bytes,
any pointer is 4 or 8 bytes ( 32 bit and 64 bit OS )
char[10] is 1 * 10 is 10 bytes.
So for class A int + char[3] is 4 + 1 * 3 = 7 bytes.
The compiler usually padds this size to a multiple of 4 or 8 for efficiency reasons, so the size could also be 8.
In gcc you could do
class __attribute((packed)) A{};
then the compiler will not padd it, but don't do that unless you have a good reason to.
+ 4
I guess (x/4+1)*4, where x is the actual size of the class. But why?
+ 4
Just wanted to add that if a function is marked virtual then another 4 or 8 bytes ( 32 bit vs 64 bit OS ) is added for the virtual jump table.
+ 2
Thanks, that was my idea too.