C++ Tutorial Index

C++ Tutorial C++ History C++ Installation C++ First Program C++ cin and cout C++ Data type C++ Variable C++ operator C++ Keywords

C++ Control Statements

C++ If C++ Nested if C++ If-else C++ If-else-if C++ Switch C++ Break C++ Continue C++ Goto C++ For loop C++ While loop C++ Do while loop

C++ Functions

C++ Call by Value C++ Call by Reference C++ Recursion Function C++ Inline function C++ Friend function

C++ Arrays

Single dimension array Two dimension array

C++ Strings

C++ Strings

C++ Inheritance

C++ Inheritance Single level Inheritance Multilevel Inheritance Multiple Inheritance Hierarchical Inheritance Hybrid Inheritance

C++ Polymorphism

C++ Polymorphism C++ Overloading C++ Overriding C++ Virtual Function

C++ Pointers

C++ Pointers C++ this pointer

C++ Exception Handling

C++ Exception Handling

C++ Constructors

C++ Constructors Default Constructor Parameterize Constructor Copy constructor Constructor Overloading Destructor

C++ File Handling

C++ File Handling C++ Writing to file C++ Reading file C++ Close file

Miscellaneous

C Vs C++ C++ Comments C++ Data Abstraction C++ Identifier C++ Memory Management C++ Storage Classes C++ Void Pointer C++ Array To Function C++ Expressions C++ Features C++ Interfaces C++ Encapsulation std::min in C++ External merge sort in C++ Remove duplicates from sorted array in C++ Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ C++ References C++ Friend Functions C++ Mutable keyword Unary Operators in C++ Initialize Array of objects with parameterized constructors in C++ Differences between #define & const in C/C++ C++ Program to Implement Shell Sort C++ Program to Implement Merge Sort Storage Classes in C Vector resize() in C++ Passing by Reference Vs. Passing by the pointer in C++ Free vs delete() in C++ goto statement in C and C++ C++ program to read string using cin.getline() C++ String Concatenation Heap Sort in C++ Swap numbers in C++ Input Iterators in C++ Fibonacci Series in C++ C ++ Program: Alphabet Triangle and Number Triangle C++ Program: Matrix Multiplication C++ Program to Print Fibonacci Triangle Stack in C++ Maps in C++ Queue in C++ C++ Bitset C++ Algorithms Priority Queue in C++ C++ Multimap C++ Deque Function Pointer in C++ Sizeof() Operators in C++ C++ array of Pointers free() Vs delete in C Timsort Implementation Using C++ CPP Templates C++ Aggregation C++ Enumeration C++ Math Functions C++ Object Class C++ Queue Initialize Vector in C++ Vector in C++ C++ STL Components Function overloading in C++ C++ Maximum Index Problem C++ find missing in the second array C++ Program to find the product array puzzle C++ Program To Find Largest Subarray With 0 Sum C++ Program To Move All Zeros To The End Of The Array C++ Program to find the element that occurs once C++ Program to find the largest number formed from an array Constructor Vs Destructor C++ Namespaces C++ OOPs Concept C++ Static C++ Structs C++ Try-Catch C++ User Defined Exceptions C++ Virtual Destructor C++ vs C# Malloc() and new in C++ Palindrome Number Program in C++ Snake Code in C++ Splitting a string in C++ Structure Vs Class in C++ Virtual Function Vs Pure Virtual Function C++ Bidirectional Iterators C++ Forward Iterators C++ Iterators C++ Output Iterators C++ Range-based For Loop Converting string into integer in C++ LCM Program in C++ Type conversion in C++ Add two numbers using the function in C++ Advantage and disadvantage friend function C++ Armstrong Number Program in C++ ATM machine program in C++ using functions Binary to Decimal in C++ Bit Manipulation in C++ C++ Constructor C++ Dijkstra Algorithm Using the Priority Queue C++ int into String C++ Signal Handling Decimal to Binary in C++ Decimal to Hexadecimal in C++ Decimal to Octal in C++ Factorial Program in C++ Function in C++ Hexadecimal to Decimal in C++ Octal to Decimal in C++ Reverse a Number in C++ Structure Vs Class in C++ C++ Forward Iterators C++ Output Iterators C++ Prime number program Constructor Overloading in C++ Different Ways to Compare Strings in C++ Program to convert infix to postfix expression in C++ SET Data Structure in C++ Upcasting and Downcasting in C++ Reverse an Array in C++ Fast Input and Output in C++ Delete Operator in C++ Copy elision in C++ C++ Date and Time C++ Bitwise XOR Operator Array of sets in C++ Binary Operator Overloading in C++ Binary Search in C++ Implementing the sets without C++ STL containers Scope Resolution Operator in C++ Smart pointers in C++ Types of polymorphism in C++

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



ADVERTISEMENT
ADVERTISEMENT