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

C++ClassObject

C++ Problem Overview


I was wondering what could be the size of an object of an empty class. It surely could not be 0 bytes since it should be possible to reference and point to it like any other object. But, how big is such an object?

I used this small program:

#include <iostream>
using namespace std;

class Empty {};

int main()
{
    Empty e;
    cerr << sizeof(e) << endl;
    return 0;
}

The output I got on both Visual C++ and Cygwin-g++ compilers was 1 byte! This was a little surprising to me since I was expecting it to be of the size of the machine word (32 bits or 4 bytes).

Can anyone explain why the size of 1 byte? Why not 4 bytes? Is this dependent on compiler or the machine too? Also, can someone give a more cogent reason for why an empty class object will not be of size 0 bytes?

C++ Solutions


Solution 1 - C++

Quoting Bjarne Stroustrup's C++ Style and Technique FAQ, the reason the size is non-zero is "To ensure that the addresses of two different objects will be different." And the size can be 1 because alignment doesn't matter here, as there is nothing to actually look at.

Solution 2 - C++

The standard states that all most derived objects have sizeof() >= 1:

> Unless it is a bit-field (class.bit), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class sub-objects may have zero size. ISO/IEC FDIS 14882:1998(E) intro.object

Solution 3 - C++

That's really an implementation detail. Once long ago, I thought it could be zero bytes or a thousand bytes, that it has no bearing on the language specification. But, after looking at the C++17 standard (expr.sizeof), sizeof is defined as always returning one or greater, no matter what.

> The size of a most derived class shall be greater than zero.

This is required for, among other things, allowing you to handle arrays of objects and pointers to them. If your elements were allowed to be zero-sized then &(array[0]) would be identical to &(array[42]), which is going to cause all sorts of havoc to your processing loops.

The reason why it may not be a machine word is that there are no elements within it that actually require it to be aligned on a word boundary (such as an integer). For example, if you place char x; int y; inside the class, my GCC clocks it at eight bytes (since the second int must be aligned in that implementation).


Having said that, that particular wording appears to have been removed from C++20, allowing for at least the possibility of objects that can take up no space. However, the following text has been added to that same section:

> When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array.

Since arrays need to be able to distinguish between elements, that would mean sizeof would have to return at least one, even if the object itself technically took up no space.

So, different wording, but the same overall effect.

Solution 4 - C++

Even though its not required to assign any memory for an empty class, but in order to make objects of empty classes, compiler assigns the minimum memory that can be assigned, which is 1 byte. This way compiler can distinguish two objects of the same empty class uniquely, and will able to assign the address of the object to a pointer of the empty class type.

Solution 5 - C++

I think it might be helpful to link to an answer explaining this good too. It is about boost::compressed_pair by Logan Capaldo.

Solution 6 - C++

There is an exception: 0-length arrays

#include <iostream>

class CompletlyEmpty {
  char NO_DATA[0];
};

int main(int argc, const char** argv) {
  std::cout << sizeof(CompletlyEmpty) << '\n';
}

Solution 7 - C++

This may help u :-) http://bytes.com/topic/c/insights/660463-sizeof-empty-class-structure-1-a

> The sizeof an empty class or structure is 1 > > The reason this happens boils down to properly implementing the > standard, one of the things the C++ standard says is that "no object > shall have the same address in memory as any other variable".... What > is the easiest way to ensure this? Make sure that all types have a > non-zero size. In order to achieve this the compiler adds a dummy byte > to structures and classes that have no data members and no virtual > functions so that they have a size of 1 rather than a size of 0 and > then they are guaranteed to have a unique memory address.

Solution 8 - C++

Allocation of 1 byte for an empty class is compiler dependent. Compilers need to make sure objects reside in different memory locations and they need to allocate non zero memory size to an object. Listen to notes on this topic here: http://listenvoice.com/listenVoiceNote.aspx?id=27

Even though compilers allocates non zero size to an empty class they also do optimizations when new classes are derived from empty classes. Listen about empty base optimization on ListenVoice's c++ programming interview questions.

Solution 9 - C++

the reason for class with no data members but having size 1 byte is that the thisstrong text must be stored in memory so that a reference or pointer can point to the object of that class

Solution 10 - C++

empty class -that class does not contain any content.

any class which is not empty will be represented by its content in memory.

now how empty class will be represented in memory? as it has no content no way to show its existance in memory, but class is present ,it is mandatory to show its presence in memory. To show empty class presence in memory 1 byte is required.

Solution 11 - C++

I think it is so because as 1 byte is the smallest memory unit that can be used as a placeholder, and it cannot give zero size as it will not be possible to create an array of objects ..

and the thing you said "This was a little surprising to me since I was expecting it to be of the size of the machine word (32 bits or 4 bytes)." will be true for reference variable(macine words) of type empty(),not size of class itself(which is abstract data type),

Solution 12 - C++

I think this question is only of theoretical interest but doesn't matter in practice.

As already pointed out by others, deriving from an empty class doesn't do any harm, as this will not consume any extra memory for the base class portion.

Moreover, if a class is empty (meaning that it - theoretically - doesn't need any per-instance memory, i.e. it doesn't have any non-static data members or virtual member functions) then all its member functions can just as well (and should) be defined as static. So there is no need to ever create an instance of this class.

Bottom line: If you find yourself writing an empty class X then just make all member functions static. You then won't need to create X objects, and derived classes will not be affected in any way.

Solution 13 - C++

#include<iostream>
using namespace std;

     
    class Empty { };
    int main()
    {
        Empty* e1 = new Empty;
        Empty* e2 = new Empty;
     
        if (e1 == e2)
            cout << "Alas same address of two objects" << endl;
        else
            cout << "Okay it's Fine to have different addresses" << endl;
     
        return 0;
    }

Output: Okay it's Fine to have different addresses

Returning size 1 ensures that the two objects will not have the same address.

Solution 14 - C++

It is nonzero to ensure that the two different objects will have different addresses. Different objects should have different addresses, so the size of an empty class is always 1 byte.

Solution 15 - C++

To an object of an empty class, 1 byte is allocated by the compiler for unique address identification. So, if a class have multiple objects they can have different unique memory location. Suppose, if a class does not have any size, what would be stored on the memory location? That’s the reason when we create an object of an empty class in the C++ program, it needs some memory to get stored, and the minimum amount of memory that can be reserved is 1 byte. So, if we create multiple objects of an empty class, every object will have a unique address.

Below the C++ code example, will always provide a unique address for both objects, created for the empty class EmptyClass.

int main()
{
	EmptyClass obj1;
	EmptyClass obj2;
     
	if (&obj1 == &obj2){
		 cout << "Both objects have same address" << endl;
	}else{
		cout << "Both objects have unique address" << endl;
	}   	
	return 0;
}

Solution 16 - C++

I think that if the size of an empty class is zero it means that it does not exist. For it (class) to exist, it requires to have at least 1 byte, since this byte is the memory/reference address.

Solution 17 - C++

It is because of this pointer , although pointer is (integer) of 4 byte but it refer to a one memory location ( one Unit ) which is 1 byte.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAshwin NanjappaView Question on Stackoverflow
Solution 1 - C++SolView Answer on Stackoverflow
Solution 2 - C++TrayManView Answer on Stackoverflow
Solution 3 - C++paxdiabloView Answer on Stackoverflow
Solution 4 - C++lalatenduView Answer on Stackoverflow
Solution 5 - C++Johannes Schaub - litbView Answer on Stackoverflow
Solution 6 - C++Konstantin NikitinView Answer on Stackoverflow
Solution 7 - C++Arsalan MehmoodView Answer on Stackoverflow
Solution 8 - C++user332764View Answer on Stackoverflow
Solution 9 - C++RamizView Answer on Stackoverflow
Solution 10 - C++GaneshView Answer on Stackoverflow
Solution 11 - C++lazarusView Answer on Stackoverflow
Solution 12 - C++kidfistoView Answer on Stackoverflow
Solution 13 - C++Sandeep_blackView Answer on Stackoverflow
Solution 14 - C++Yadvendra YadavView Answer on Stackoverflow
Solution 15 - C++Disha GugnaniView Answer on Stackoverflow
Solution 16 - C++HoneyView Answer on Stackoverflow
Solution 17 - C++Narayan das khatriView Answer on Stackoverflow