Thursday, September 25, 2014

Using Enumeration in C++

Enumeration in C++ is a user defined type that contains a set of constant values. An enumeration consists of an identifier and a list of types. Every type in an enumeration corresponds to a constant value. Default value for the first type is integer 0 and the next one gets the integer value 1. But an enumeration type can have a value other than default integer 0. Therefore an enum type can be casted to integer.


Following sample project created by qt creator and contains following files:
1- UsingEnumeration.pro
2- device.h
3- device.cpp
4- main.cpp



UsingEnumeration.pro file contains project configuration.

TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt
SOURCES += main.cpp \
    device.cpp
HEADERS += \
    device.h

device.h header file contains definition for Device class and Status enumeration.

#ifndef DEVICE_H
#define DEVICE_H

namespace UsingEnumsSample
{

enum Status {
    IDLE = 0,
    ACTIVE = 1,
    DEAD = 2
};

class Device
{
public:

    Device();
    void setStatus(Status pStatus);
    Status getStatus();

private:
    Status status;
};

}

#endif // DEVICE_H


device.cpp file contains implementation for Device class. setDevice method accepts an enumerator and assigns the passed value to Device class private enumeration member.

#include "device.h"

namespace UsingEnumsSample
{

Device::Device()
{
}

void Device::setStatus(Status pStatus)
{
    status = pStatus;
}

Status Device::getStatus()
{
    return status;
}

}

main.cpp method creates a Device instance and calls its setStatus and getStatus methods to set the Status value to the private Status enumeration member.

#include <iostream>
#include "device.h"

using namespace std;
using namespace UsingEnumsSample;

int main()
{
    Device device;
    device.setStatus(ACTIVE);
    cout << device.getStatus() << endl;
    device.setStatus(IDLE);
    cout << device.getStatus() << endl;
    return 0;
}

When the main method is executed, values of the Status member is displayed on the terminal which are consequently 1 and 0 as the program runs.