Home > Backend Development > C++ > body text

Can You Inherit From an Enum Class in C ?

Mary-Kate Olsen
Release: 2024-10-31 21:27:29
Original
309 people have browsed it

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>
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!