1
class test
{
public:
    enum t_number
    {
        ZERO,
        ONE
    };

    enum t_test
    {
        TWO,
        THREE
    };
};

Why the size of the above class is 1 and not 8?

And when I do this in main()

cout << "value of enum"<< test::ONE

I get output as 1.

Does that mean memory is allocated for the enum?

  • 5
    Because you declared only types in your class (no members) and the minimum size of a class is 1. – drescherjm Jan 17 '18 at 14:46
  • 2
    Because you don't have any member variables. An object still needs to take some place, to be addressable, so it still is one single byte so it could be stored in memory. – Some programmer dude Jan 17 '18 at 14:46
  • You are not declaring data members... – JFMR Jan 17 '18 at 14:46
  • Why would it be 8? It contains no data. C++ doesn't allow 0 size objects (because that would lead to various bad things like multiple objects having the same address and arrays behaving super weird), so 1 is the ideal choice. – nwp Jan 17 '18 at 14:46
  • Possible duplicate of [Why is the size of an empty class in C++ not zero?](https://stackoverflow.com/questions/2362097/why-is-the-size-of-an-empty-class-in-c-not-zero) – Raymond Chen Jan 17 '18 at 15:34

1 Answers1

0

Only data have size, you're not setting data in your class, you're defining types of data.

For the second part, recently added, you're asking to display test::ONE, like in C, enums are an abstraction of unsigned integers, so when you type :

enum foo {
    bar,
    baz,
    qux
};

It's exactly the same as typing

enum foo {
    bar = 0,
    baz = 1,
    qux = 2
};

So when you type this in your main

cout << "value of enum"<< test::ONE;

You just implicitely converting your test::ONE in its integer value.

Note that this implicit conversion would not exist with enum class in c++11.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Steranoid
  • 64
  • 6