Why is the size of an empty class not zero in C++? Explain with example

The size of an empty class is not zero. It is 1 byte generally.
See the following example.

Output:

The size of empty class is nonzero, but the addresses of the two classes are not equal to ensure that see the below example

See the output

See another sample; there is an interesting rule that says that an empty base class need not be represented by a separate byte. So compilers are free to make optimization in case of empty base classes. Which means the size of the derived class is the total size of the base and derived class  As an exercise, try the following program on your compiler.

Output of the above program is:

In the above example the size of the derived class is the size of the base and derived class

Output is

If the derived class is inherited virtual base class, in this case the size of the class is different, see here once

The output of the above program is

Why class size depend only on data members and not on member functions? The functions of the class is not saved inside the object, only the member variables are stored in the object. So the size of the class becomes the total size of the member variables of the class.

What is the size of the class when the base class contains virtual functions? Existence of virtual function(s) will add 4 bytes of virtual table pointer in the class, which will be added to size of class. Again, in this case, if the base class of the class already has virtual function(s) either directly or through its base class, then this additional virtual function won’t add anything to the size of the class. Virtual table pointer will be common across the class hierarchy. That is

The output of the above program is

In the example above, sizeof(BaseCls) will be 8 bytes–that is sizeof(int) + sizeof(int) + sizeof(vptr). sizeof(Derived_1) will be 16 bytes.

Now Derived will set the vptr to its own virtual function table.

Mainly the size of the class depends on the below factors

1. Depends on the order of data members
2. Depends on the  size of all non-static data members
3. Depends on the byte alignment or byte padding
4. Depends on the  size of its immediate base class
5. The existence of virtual function(s) (Dynamic polymorphism using virtual functions).
6. Compiler being used 7. Depends on the mode of inheritance (virtual inheritance)