C++ – Getting the Size of Member Variable

c++c++11

If there is a POD structure, with some member variables, for example like this:

struct foo
{
   short a;
   int b;
   char c[50];
   // ...
};

Is there a way to get the size of a member variable in bytes, without creating an object of this type?

I know that this will work:

foo fooObj;
std::cout << sizeof( fooObj.a ) << std::endl;
std::cout << sizeof( fooObj.b ) << std::endl;
std::cout << sizeof( fooObj.c ) << std::endl;

Would the following be optimized by the compiler and prevent the construction of an object?

std::cout << sizeof( foo().a ) << std::endl;

Best Answer

You can do that in C++0x:

sizeof(foo::a);
Related Question