Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the size of my class zero? How can I ensure that different objects have different address?

Tags:

c++

class

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;
}        
like image 837
SAC Avatar asked Nov 30 '22 20:11

SAC


1 Answers

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.

like image 200
AnT Avatar answered Dec 03 '22 09:12

AnT