Alex Rivera | Logout

Getting the size of member variable

Asked 2011-05-12T10:50:05.993
26

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;
Edit
Report

1 Answer

0

You can create macro wrapper of what @Erik suggested as:

#define SIZE_OF_MEMBER(cls, member) sizeof( ((cls*)0)->member )

And then use it as:

cout << SIZE_OF_MEMBER(foo, c) << endl;

Output:

50

Demo : http://www.ideone.com/ZRiMe

answered 2011-05-12T11:04:28.570

Your Answer