Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 506
alireza sadeghpour Avatar asked Nov 29 '22 00:11

alireza sadeghpour


1 Answers

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.

like image 112
Some programmer dude Avatar answered Dec 10 '22 23:12

Some programmer dude