For example: A complex class
class complex
{
public:
complex(double r = 0, double i = 0)
: re(r), im(i) {}
complex &operator += (const complex &);
double real() const { return re; }
double imag() const { return im; }
private:
double re, im;
};
I can get the size of complex by:
complex c(1, 2);
cout << sizeof(c) << endl;
But why I can also get the size of the complex by:
cout << sizeof(complex) << endl;
I didn't instantiate a complex object. How does the computer know the actual size of complex without creating an object to test it?
I don't believe that the compiler contains all data type length information for different bits of OS. And the program can allocate memory for 'long' type differently on 32bit or 64bit OS. There must have a way to decide data length on run-time.
Objects of type complex
are all of same size, hence you don't need to create an object to know its size.
sizeof(x)
is a constant expression. It is not evaluated at runtime. A class definition is necessary and sufficient for the compiler to know the size of objects of that type. Thats also the reason you cannot use sizeof
with an incomplete type (declared but not defined). And the compiler is using that information all the time, when you pass a complex
by value to a function, when you create an object of type complex
, etc.
The size of a type is the size of its members plus padding. For more details I refer you to Why isn't sizeof for a struct equal to the sum of sizeof of each member?.