Home  >  Article  >  Backend Development  >  Can You Inherit From an Enum Class in C ?

Can You Inherit From an Enum Class in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 21:27:29309browse

Can You Inherit From an Enum Class in C  ?

Base Enum Class Inheritance in C

One common question that arises in C programming is whether it's possible to inherit an enum from another enum. This allows for the creation of a derived enum that expands upon the values defined in the base enum.

The provided code sample illustrates how to achieve base enum class inheritance in C :

<code class="cpp">#include <iostream>
#include <ostream>

class Enum
{
public:
    enum
    {
        One = 1,
        Two,
        Last
    };
};

class EnumDeriv : public Enum
{
public:
    enum
    {
        Three = Enum::Last,
        Four,
        Five
    };
};

int main()
{
    std::cout << EnumDeriv::One << std::endl;
    std::cout << EnumDeriv::Four << std::endl;
    return 0;
}</code>

In this example, the EnumDeriv class inherits from the Enum class. The Three value in EnumDeriv is defined to start from the end of the values defined in Enum, allowing for a seamless continuation of values.

When compiling and running the code, it will output:

1
4

This demonstrates the successful inheritance of the Enum class's values by EnumDeriv and the ability to define additional values in the derived enum. This pattern can be useful for organizing and extending enumeration values in a more hierarchical manner.

The above is the detailed content of Can You Inherit From an Enum Class in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn