- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why is the size of an empty class not zero in C++?
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 −
#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
#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++)
#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