Home > Backend Development > C++ > body text

Can C Enumerations Inherit from Other Enumerations?

Mary-Kate Olsen
Release: 2024-10-31 01:45:29
Original
947 people have browsed it

Can C   Enumerations Inherit from Other Enumerations?

Inheritance of Enumerations in C

Encapsulation is a fundamental programming principle that promotes code reusability and maintainability. In C , inheritance allows classes to inherit properties and functionalities from their base classes. Can we extend this concept to enumerations?

The question posed is: is there a way to inherit an enum from another enum in C ? Specifically:

<code class="cpp">enum eBase 
{
   one=1, two, three
};


enum eDerived: public eBase
{
   four=4, five, six
};</code>
Copy after login

Overcoming the Limitations

While the syntax shown above is not directly supported, there is a pattern to achieve similar functionality:

<code class="cpp">class Enum
{
public:
    enum
    {
        One = 1,
        Two,
        Last
    };
};

class EnumDeriv : public Enum
{
public:
    enum
    {
        Three = Enum::Last,
        Four,
        Five
    };
};</code>
Copy after login

Here, we define Enum as a class containing an enumerated type. EnumDeriv inherits publicly from Enum. Notice that both enumerations use the enum keyword within their respective classes.

Accessing Inherited Values

To access the inherited values, we prefix the enumeration name with the class name, e.g., EnumDeriv::One. The Last constant is also accessible from EnumDeriv, allowing seamless continuity.

Demonstration

<code class="cpp">int main()
{
    std::cout << EnumDeriv::One << std::endl;
    std::cout << EnumDeriv::Four << std::endl;
    return 0;
}</code>
Copy after login

Output:

1
4
Copy after login

The above is the detailed content of Can C Enumerations Inherit from Other Enumerations?. 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!