I created a class but its size is zero. Now, how can I be sure that all objects have different addresses? (As we know, empty classes have a non-zero size.)
#include<cstdio>
#include<iostream>
using namespace std;
class Test
{
int arr[0];//Why is the sizezero?
};
int main()
{
Test a,b;
cout <<"size of class"<<sizeof(a)<<endl;
if (&a == &b)// now how we ensure about address of objects ?
cout << "impossible " << endl;
else
cout << "Fine " << endl;//Why isn't the address the same?
return 0;
}
Your class definition is illegal. C++ does not allow array declarations with size 0
in any context. But even if you make your class definition completely empty, the sizeof
is still required to evaluate to a non-zero value.
9/4 Complete objects and member subobjects of class type shall have nonzero size.
In other words, if your compiler accepts the class definition and evaluates the above sizeof
to zero, that compiler is going outside of scope of standard C++ language. It must be a compiler extension that has no relation to standard C++.
So, the only answer to the "why" question in this case is: because that's the way it is implemented in your compiler.
I don't see what it all has to do with ensuring that different objects have different addresses. The compiler can easily enforce this regardless of whether object size is zero or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With