Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the size of member variable

Tags:

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;
like image 922
BЈовић Avatar asked Sep 10 '25 15:09

BЈовић


1 Answers

You can do that in C++0x:

sizeof(foo::a);
like image 193
Cat Plus Plus Avatar answered Sep 12 '25 12:09

Cat Plus Plus