tags:

views:

149

answers:

2

Hi,

I am not getting Why Size of Class with a member function is 1 byte..While member function is 4 bytes in the following example.

class Test
{
    public:
      Test11()
      {
       int m = 0;
      };
};

int main() 
{
    Test t1;
    int J = sizeof(t1);
    int K = sizeof(t1.Test11());
    return 0;
}

Here J becomes 1 Byte and K becomes 4 bytes. If K=4, then why size of class is not 4 bytes instead it shows 1 Byte

+12  A: 

The function itself is not actually stored in the class.

Only the class's data members (and possibly its vtable pointer, if it has one) affect its size. The function itself lives in the executable code region, and all instances of the same type of class use that one definition of the function. The compiler does not actually copy out the entirety of a function body every time you create a new instance of the class.

Also, sizeof(t1.Test11()) does not mean "the size of the function Test::Test11's executable code in bytes." It means "the size of the type returned by Test::Test11".

Crashworks
It should also be noted that 1 is the minimum value sizeof will ever return. Otherwise, arrays would break badly.
derobert
+2  A: 

Function implementation is not contained in each instance of a class, so instance of a class could have size 0, but it is not. Bjarne Stroustrup wrote here why is the size of an empty class not zero?

Kirill V. Lyadvinsky