×

C++ Enumeration

C++ Enumeration

In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets where the sets me of various types.

Let us consider a week which has 7 days or all four directions. This kind of set is served very well using Enum in C++.

Enum in C++ is final implicit and constants are static. It can be thought of as classes that have well-defined or fixed sets of constants.

Consider these arguments to learn more about Enum:

  1. It can be traversed.
  • It can have methods, fields, and constructors.
  • It can be easier with switch statements.
  • It enhances type safety.
  • It cannot extend classes. Although, it may implement various interfaces by internally extending the enum class.

Generally, enum is a keyword used for enumeration in C++. It is used specifically with integral constants to enhance code readability and maintainability.

Consider the following syntax of enum:

enum enum_name {constant1, constant2, ……..};

Example:

  enum animals{cow, horse, dog, cat};
  enum card_deck{ace=4, kind=4, spade=4}; 

Let us look at some programming examples to understand better.

Example 1: Generic use

 #include<bits/stdc++.h>
 using namespace std; 
 enum animals { Dog, Cat, Wilderbeast, Cow }; 
 int main() 
 { 
     animals pet; 
     pet = Dog; 
     cout << "Pet: " << pet+1<<endl; 
     return 0; 
 } 

Output:

C++ Enumeration

Explanation:

The above code is the simplest demonstration of working with enum in C++. We have assigned the enum keyword before the enum variable's name and have contained it in the various animal's names. The task is to return the position of the animal. To do this, we assigned the enum variable with another variable pet that holds the container's value. The container value with their respective position is then displayed on the console.

Note: There can be an N number of values in the containers. It is better to use lists or arrays in such cases, which allow random access. Although enum provides us the same features, it may increase the space complexity if the container's size is not defined on priority.

Example 2: Using Switch Statement

 #include <bits/stdc++.h>
 using namespace std;
 int main()
 {
     enum Direction { North, South };
     Direction direction = North;
     switch (direction)
    {
     case North:
         cout << "Direction is North";
         break;
     case South:
         cout << "Direction is South";
         break;
     default:
         cout << "Direction can be either North or South";
  }
     return 0;
 } 

Output:

C++ Enumeration

Explanation:

We have used the enum keyword with enumerated key names as directions with two values: North and South in the above code. We have also associated the enumerated keyword with the direction, which is assigned value as North initially. We have defined a switch case that takes direction as an argument and checks if the argument is North or South. If any of these two directions exist in the program, it will be printed, or else the default case will be displayed on the console through the switch statement.

Example 3: Traversing with the enum

 #include <bits/stdc++.h>
 using namespace std;
 enum home_groceris
 {
     Brush,
     Paste,
     Toothskie,
     Watergun,
     Floss,
     Pan,
     Spoon
 };
 int main()
 {
     int x;
     // Traversing the home_groceris enum
     for (x = Brush; x <= Spoon; x++)
         cout << x << " ";
     return 0;
 } 

Output:

C++ Enumeration

Explanation:

The above code is a demonstration of traversing using enum. We have defined an enumerated name as home_groceries and assigned certain items in the containers. In the driver code, we have defined a variable x that will iterate over the container's items from beginning to end. The output is shown in the picture is the respective count or, say, indexes of the items present in the enumerated container.

Advantages and Disadvantages of Enum

  1. Enum works well with string, but sometimes they don't work properly with numbers.
  • Since enumeration is space-concerned, it possesses no capability to work with additional meta-data.
  • While iterating through enumeration containers, enum is sufficient only in case the container is not too large. Random accessing is easy yet time-consuming.
  • Enumerators can implement many interfaces, but it fails in extending classes.
  • The advantage of using enumerators in C++ includes a lower maintenance requirement, improved program readability, and better-debugging capability.
  • Another advantage is that enumerated constants are generated automatically by the compiler. Conversely, symbolic constants must be manually assigned values by the programmer

Related Topics

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.

Differences between #define & const in C/C++

 Differences between #define & const in C/C++ A preprocessor directive is #define. The preprocessor replaces things defined by #define prior to starting compilation. In this chapter, we'll learn about the member, variable,...

3 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++ Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have...

3 minutes read.

Dynamic Constructor in C++

Dynamic constructors create dynamic memory by using a dynamic memory allocator new within the constructor. This allows us to initialize objects dynamically. The term dynamic constructor is used when memory...

2 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.