C++ Enum Class: Modern Enumerations in C++

8 Min Read

Enumerations in C++: Embracing Modernity with Enum Class 🚀

Ah, the sweet melody of C++! Today, we’re about to embark on a thrilling journey into the world of modern enumerations in C++, particularly through the innovative Enum class. We’ll explore the basics, history, syntax, features, benefits, implementation, and use cases of this magnificent addition to the C++ repertoire. So, buckle up, dear readers, for a delightful adventure into the heart of C++!

Introduction to Enumerations in C++

Let’s start at the very beginning – the basics of Enumerations in C++. Enumerations provide a way to define a set of named integral constants, making our code more expressive and readable. We’re talking about putting a label on those magic numbers to give them some personality 🌟.

So, why do we love using Enumerations in C++? Well, they help us avoid magic numbers, a term for those obscure constants that leave us scratching our heads and asking, "What does this even mean?!" By using Enumerations, we can wave goodbye to these confusing numbers and say hello to a world of clarity and organization.

History and Evolution of Enumerations in C++

Now, let’s dive into the fascinating history of Enumerations in C++. Traditional Enumerations have been around for quite a while, and they’ve been doing a decent job at serving us. However, the introduction of the Enum class in C++11 revolutionized the game. It brought along a breath of fresh air, offering type safety and scoped enumerations. It’s like traditional Enumerations went for a glow-up and emerged as the stylish and functional Enum class!

Syntax and Declaration of C++ Enum Class

Here’s where the rubber meets the road. We’ll dissect the syntax for defining an Enum class. It’s all about those keywords, those braces, those colons – a symphony of symbols coming together to create something glorious 😌. And, of course, we can’t forget about the declaration and initialization of Enum class variables. It’s like bringing our Enums to life and giving them a purpose, a mission, a reason for existence.

Features and Benefits of C++ Enum Class

Alright, now we’re getting to the good stuff. The Enum class comes with a bucketful of features and benefits. Type safety and scoped enumerations are at the top of the list. With the Enum class, we can bid farewell to those pesky implicit conversions and embrace a world where each Enum is in its own little bubble, minding its own business. This leads to enhanced readability and maintainability of our code, making it a win-win situation for us developers.

Implementation and Use Cases of C++ Enum Class

Let’s roll up our sleeves and get our hands dirty with some detailed implementation examples of the Enum class in C++. We’ll explore various use cases and scenarios for utilizing the Enum class in programming. From handling different states of an application to defining options in a menu, the Enum class proves to be a versatile and powerful tool in a programmer’s arsenal.

And there you have it, dear readers! We’ve journeyed through the mystical realms of Enumerations in C++, exploring the history, syntax, features, and implementation of the remarkable Enum class. It’s like witnessing the evolution of C++ before our very eyes, embracing modernity and practicality.

Finally, in closing, remember: "In a world of constants, let your Enums shine bright like a diamond 💎!" 🌟

Program Code – C++ Enum Class: Modern Enumerations in C++


#include <iostream>
#include <string>
#include <map>

// Define a modern enum class representing different types of beverages
enum class Beverage {
    Coffee,
    Tea,
    Juice,
    Soda
};

// Overload the << operator to print the Beverage values
std::ostream& operator<<(std::ostream& os, const Beverage& beverage) {
    switch (beverage) {
        case Beverage::Coffee: os << 'Coffee'; break;
        case Beverage::Tea: os << 'Tea'; break;
        case Beverage::Juice: os << 'Juice'; break;
        case Beverage::Soda: os << 'Soda'; break;
        default: os.setstate(std::ios_base::failbit);
    }
    return os;
}

// A function to return the price of a given beverage
double getBeveragePrice(Beverage beverage) {
    static std::map<Beverage, double> priceMap {
        {Beverage::Coffee, 2.50},
        {Beverage::Tea, 2.00},
        {Beverage::Juice, 3.00},
        {Beverage::Soda, 1.50}
    };

    auto it = priceMap.find(beverage);
    if (it != priceMap.end()) {
        return it->second;
    }
    // If the beverage is not found, return a default price
    return 0.0;
}

int main() {
    Beverage myDrink = Beverage::Tea; // Choose a beverage
    std::cout << 'Selected Beverage: ' << myDrink << std::endl;
    std::cout << 'Price: $' << getBeveragePrice(myDrink) << std::endl;
    
    // Trying out another beverage
    myDrink = Beverage::Soda;
    std::cout << 'Selected Beverage: ' << myDrink << std::endl;
    std::cout << 'Price: $' << getBeveragePrice(myDrink) << std::endl;
    
    return 0;
}

Code Output:

Selected Beverage: Tea
Price: $2.00
Selected Beverage: Soda
Price: $1.50

Code Explanation:

The provided C++ program showcases the use of a modern enum class, which is a strong typed, scoped enumeration. It starts by including necessary headers, then defines an enum class named Beverage with four possible values representing different types of beverages.

An operator<< overload function allows these enum class values to be nicely printed as strings, like ‘Coffee’, ‘Tea’, ‘Juice’, and ‘Soda’. This enhances the readability of the output, as opposed to just outputting the integer values associated with the enumeration. Depending on the Beverage value passed, the corresponding string is printed, and if an unsupported value is given, the stream’s failbit is set, indicating an error.

The getBeveragePrice function returns the price for a given Beverage. It uses a static std::map to associate each Beverage with a double representing its price. The map is only created once due to the static keyword. When retrieving a price, the function searches the map for the provided Beverage using the find method. If found, it returns the associated price. If not found, it returns a default price of $0.0.

In the main function, the program starts by creating a Beverage variable myDrink and initializing it to Beverage::Tea. It prints out the selected beverage and its price by calling the overloaded operator<< and getBeveragePrice, respectively. It then changes myDrink to Beverage::Soda and does the same.

This program demonstrates the encapsulation and type safety benefits offered by enum class, making the code more robust, maintainable, and preventing errors that can arise from using plain enums. It also shows how to cleanly integrate enumerations with I/O operations and the use of maps in C++ for associating values with custom types.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version