
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- What is the size of an object of an empty class in C++?
- Why zero (0) is the first number?
- Why is address zero used for the null pointer in C/C++?
- Creating an empty case-sensitive HybridDictionary Class in C#
- Why it shows 0 instead of empty string whenever I insert an empty string into a MySQL column which is declared as NOT NULL?
- Different ways of checking if an array is empty or not in PHP
- Why singleton class is always sealed in C#?
- How it is possible to insert a zero or an empty string into a MySQL column which is defined as NOT NULL?
- Why does the indexing start with zero in C# arrays?
- Why C/C++ array index starts from zero?
- Why array index starts from zero in C/C++ ?
- deque::empty() and deque::size() in C++ STL
- queue::empty() and queue::size() in C++ STL
- stack empty() and stack size() in C++ STL
- What is the Capacity property of an ArrayList class in C#?