Can anyone explain why the sizeof function returns different values ​​in the code below?

advertisements

Can anyone explain me why the sizeof function returns different values in the code below?

//static member
class one
{
  public :
  static const int a = 10;
};
//non static member
class two
{
  public :
  int a;
};
int main()
{
  cout << sizeof(one);       //print 1 to lcd
  cout << sizeof(two);       //print 4 to lcd,differ from size of one class
}


The first thing you should learn is that sizeof is not a function, it's an operator just like + or ||.

Then as for your question. Static member variables are not actually in the class the same way non-static member variables are, so a class with only static members will have zero size. But at the same time all objects needs to be addressable, and therefore have, which is why sizeof give you 1 for the first class.