I have a C++ question. I wrote the following class:
class c
{
int f(int x, int y){ return x; }
};
the sizeof() of class c returns \"1\"
Member functions are, essentially, the same as regular functions, they just get a hidden this
paramter. So each instance of a given type does not need to carry around copies of its member functions; the compiler just keeps track of the regular functions, and provides an appropriate this
paramter for you. So no matter how many functions a given type has, there is no need for its size to change. When you get into complicated inheritance with virtual functions and whatnot, this changes slightly, but in the end the number of functions continues to have no impact on the final size of the object.
The initial size of one byte is because all objects have to occupy some space, so that you can be guarenteed no two objects occupy the same space. Consider an array... a[5]
is the same as *(a + 5)
, and adding to a pointer increases the memory address by the size of the object. if sizeof(a)
were 0
, then all the elements of the array would collapse down to the same address.
That the objects type of some space is mandated by the standard... that the size be equal to exactly one is not. sizeof(c)
in your case could be 23, but there's no reason for it.
For completeness, it is possible for a sub-object to have a size of zero. The empty base optimization allows for a base class to not occupy any actual memory if it does not need to. So sizeof(Base) == sizeof(Derived)
might be true, even though formally Derived
contains an instance of Base
hidden inside it. This is allowed by the standard, but not mandated by it... MSVC, for instance, does not make use of it in some situations.