class Test
{
int x;
};
int main()
{
cout << sizeof(Test) ;
return 0;
}
Output : 4
I just want to ask that even i am not created any object of class Test why it prints 4 ?
class Test
{
int x;
};
int main()
{
cout << sizeof(Test) ;
return 0;
}
Output : 4
I just want to ask that even i am not created any object of class Test why it prints 4 ?
sizeof(X)
is the number of bytes an X
takes when created. A call to new
tends to use a few more bytes for memory use overhead, but an automatic storage (on-stack or local or global or static etc) array of X[N]
will take N*sizeof(X)
memory in practice (a little extra maybe for function local statics due to thread safety requirements).
It has nothing to do with the amount of memory the type itself takes.
Classes themselves use memory if they have methods that are not optimized away, if they have a vtable (caused by use of the virtual
keywords), or similar. Then memory storing code or virtual function tables may exist outside of the memory costs of instances of the class.
Within the C++ language itself, there is no way to determine how much memory the class itself takes, nor no reliable way to determine what the new
overhead is. You can usually puzzle that out by looking at the runtime behaviour, or the code for the compiler or runtime libraries, for a given platform.
A class
or or a struct
is basically a kind of datatype (not exactly the datatype), so a data type will occupy memory only when a variable of its type is created. So a class
will occupy space when it is instantiated. If a class
has a static
member variable it will occupy space even if there is no instantiation.