C++ Enums, Structs and Namespaces

enum class

An enum class (scoped enum) is a set of named constants. It is safer than the old enum, because the names do not leak out, and there is no hidden conversion to int.

#include <iostream>

enum class Color { Red, Green, Blue };

std::string_view name(Color c) {
    switch (c) {
        case Color::Red:   return "Red";
        case Color::Green: return "Green";
        case Color::Blue:  return "Blue";
    }
    return "?";
}

int main() {
    Color c = Color::Green;
    std::cout << name(c) << ' ' << static_cast<int>(c) << '\n';
}
Output

Green 1

enum class Level { Low, High };

int main() {
    int x = Level::High;                 // no hidden conversion
}
Output

Mix.cpp: In function 'int main()':
Mix.cpp:4:20: error: cannot convert 'Level' to 'int' in initialization
4 | int x = Level::High; // no hidden conversion
| ~~~~~~~^~~~
| |
| Level
Mix.cpp:4:9: warning: unused variable 'x' [-Wunused-variable]
4 | int x = Level::High; // no hidden conversion
| ^

struct for simple data

#include <iostream>
#include <string>
#include <vector>

struct Student {
    std::string name;
    int marks;
};

int main() {
    std::vector<Student> students = {{"Riya", 88}, {"Aman", 72}};
    for (const auto& [name, marks] : students) {                // structured bindings
        std::cout << name << ": " << marks << '\n';
    }
}
Output

Riya: 88
Aman: 72

Namespaces

A namespace groups names, so two libraries can both have a function called print.

#include <iostream>

namespace math {
    int square(int n) { return n * n; }
    namespace extra {
        int cube(int n) { return n * n * n; }
    }
}

namespace shop {
    int square(int n) { return n; }               // another square: no clash
}

int main() {
    std::cout << math::square(5) << ' ' << shop::square(5) << ' ' << math::extra::cube(3) << '\n';

    using math::square;                           // bring one name in
    std::cout << square(4) << '\n';

    namespace m = math::extra;                    // a short alias
    std::cout << m::cube(2) << '\n';
}
Output

25 5 27
16
8

using namespace std;

It is short, but it brings all the names of std into your scope and can cause clashes. It is fine in small examples and in a .cpp file, but never put it in a header file.

Note: Use enum class instead of plain enum in new code. Next: C++ Exceptions.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.