Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

sizeof

Possible Duplicate:
C++: What is the size of an object of an empty class?

Why does the following output 1?

#include <iostream>  class Test { };  int main() {     std::cout << sizeof(Test);     return 0; } 
like image 288
shreyasva Avatar asked Mar 02 '10 09:03

shreyasva


People also ask

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

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.

Why size of empty class or struct is one in C++?

So, according to the C standard, it was decided to keep the size of the empty structure to zero. In C++, the Size of an empty structure/class is one byte as to call a function at least empty structure/class should have some size (minimum 1 byte is required ) i.e. one byte to make them distinguishable.

What is the memory of an empty class?

An Empty class's object will take only one byte in the memory; since class doesn't have any data member it will take minimum memory storage.

What is the size of an empty class in bytes?

Size of an empty class is not zero. It is 1 byte generally.


2 Answers

The standard does not allow objects (and classes thereof) of size 0, since that would make it possible for two distinct objects to have the same memory address. That's why even empty classes must have a size of (at least) 1.

like image 147
Péter Török Avatar answered Oct 21 '22 12:10

Péter Török


To ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects.

See Stroustrup for complete answer.

like image 42
Maurits Rijk Avatar answered Oct 21 '22 11:10

Maurits Rijk