Home > Article > Backend Development > 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>
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>
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>
Output:
1 4
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!