4

Possible Duplicate:
Empty class in C++

class Class1
{
char c;
};

class Class2
{
};

What is the size of Class1 and Class2?

In VC6, I got both 1. can someone explain this?

Community
  • 1
  • 1
mpouse
  • 51
  • 1
  • @jleedev: I disagree, his class is not just a empty class but, also one with a `char c`. –  Oct 11 '10 at 01:48
  • 1
    @thyrgyle: Close as a duplicate doesn't mean the questions are exactly the same, it means that understanding an existing question and answers also covers the new question as well. That's the case here. Clearer example of the distinction between identical and duplicate: Q1: What are the first five prime numbers? Q2: What is the third prime number? Q2 can be closed as a dupe of Q1. – Ben Voigt Oct 11 '10 at 01:58
  • @Ben: That's a great example. I'm stealing it. – GManNickG Oct 11 '10 at 03:35

1 Answers1

6

No class can ever have size less than one, because pointer arithmetic (specifically the subtraction operator) can divide by the size, and division by zero is undefined. It's also necessary that every instance have a unique address, which means that at least one byte of address space has to be given to each, hence minimum size is again one.

So sizeof (Class1) == 1 because that's what is needed for the content, and sizeof (Class2) == 1 because that's the minimum allowed.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720