Why is the size of an empty class not zero in C++?

C++Server Side ProgrammingProgramming

Suppose we have one empty class in C++. Now let us check whether its size is 0 or not. Actually, the standard does not permit objects (or classes) of size 0, this is because that would make it possible for two distinct objects to have the same memory location. This is the reason behind the concept that even an empty class must have a size at least 1. It is known that size of an empty class is not zero. Generally, it is 1 byte. See the below example.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include<iostream>
using namespace std;
class MyClass {
};
int main() {
   cout << sizeof(MyClass);
}

Output

1

It clearly shows that an object of one empty class will take at least one byte to ensure that the two different objects will have different addresses. See the below example.

Example

 Live Demo

#include<iostream>
using namespace std;
class MyClass {
};
int main() {
   MyClass a, b;
   if (&a == &b)
      cout <<"Same "<< endl;
   else
      cout <<"Not same "<< endl;
}

Output

Not same

For dynamic allocation also, the new keyword returns different address for the same reason.

Example (C++)

 Live Demo

#include<iostream>
using namespace std;
class MyClass {
};
int main() {
   MyClass *a = new MyClass();
   MyClass *b = new MyClass();
   if (a == b)
      cout <<"Same "<< endl;
   else
      cout <<"Not same "<< endl;
}

Output

Not same
raja
Published on 27-Aug-2020 13:32:52
Advertisements