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.
Let us see the following implementation to get better understanding −
#include<iostream> using namespace std; class MyClass { }; int main() { cout << sizeof(MyClass); }
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.
#include<iostream> using namespace std; class MyClass { }; int main() { MyClass a, b; if (&a == &b) cout <<"Same "<< endl; else cout <<"Not same "<< endl; }
Not same
For dynamic allocation also, the new keyword returns different address for the same reason.
#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; }
Not same