Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is an empty class and an empty struct compiled?

Does the C++ standard dictate the compilation layout of the class and struct? How are they compiled differently especially if they are empty?

like image 476
unj2 Avatar asked Jun 04 '12 20:06

unj2


People also ask

How do you define an empty struct?

An empty structIt occupies zero bytes of storage. As the empty struct consumes zero bytes, it follows that it needs no padding. Thus a struct comprised of empty structs also consumes no storage.

How do I make an empty struct?

array = struct. empty(n,0);

What is empty structure in C++?

6.19 Structures with No Members GCC permits a C structure to have no members: struct empty { }; The structure has size zero. In C++, empty structures are part of the language. G++ treats empty structures as if they had a single member of type char .

What does an empty class contains?

Empty class: It is a class that does not contain any data members (e.g. int a, float b, char c, and string d, etc.)


1 Answers

It does in a way, it says that it has to allocate space for it unless certain cases when its used as a base class (known as Empty Base Class Optimization). This is to guarantee that different objects have different addresses.

They are compiled the same given that struct and class are the same thing, except for the default access specifier. In C++11 the notion of standard-layout classes/structs is introduced, and guarantees that the memory layout for empty classes to be the same.

like image 174
K-ballo Avatar answered Oct 23 '22 17:10

K-ballo