Native enums in C++

I always thought that enums in C++ always had the same integer as the underlying type. I discovered today that need not be the case and they can have any integral type as an underlying type. See the example below as an example.

 cl native_enum.cpp /EHs /wd4996 /I"<Insert boost::format path here>"

 I used boost::format for helping with formatting the string, You can
 replace it with printf if you like.

 Disabled warning 4996 that is a spurious warning.

    sizeof(vehicle): 1
    sizeof(creature: 2
    sizeof(home):    4

#include <iostream>
#include <boost/format.hpp>
using namespace std;

enum vehicle : char { car, boat, plane };
enum creature: short { dog, cat, eagle };
enum home: int { house, apartment, mansion};
int main(int argc, char *argv[])
    cout<<boost::format("sizeof(vehicle): %d") % sizeof(vehicle) <<endl;
    cout<<boost::format("sizeof(creature: %d") % sizeof(creature) <<endl;
    cout<<boost::format("sizeof(home):    %d") % sizeof(home) <<endl;
    return 0;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: