Home >Backend Development >C++ >Why is the 'typedef super' idiom so commonly used in C ?
Using "super" in C
Introduction
In C , the use of the "typedef super" idiom to enable access to the base class as "super" has become a common practice, especially among experienced programmers. This idiom involves creating a typedef within a derived class that references the base class. Here's a brief explanation of how it works and the benefits it offers:
How It Works
The following code demonstrates the "typedef super" idiom:
class Derived : public Base { typedef Base super; // Creates an alias for Base
With this typedef, you can use the "super" alias to access the base class in various scenarios, such as in constructors:
Derived(int i, int j) : super(i), J(j) {}
or when calling methods of the base class within overridden versions:
void Derived::foo() { super::foo(); // Calls the overridden version of foo in Derived }
The idiom can be used for chaining, allowing access to the base class of the base class:
class DerivedDerived : public Derived { typedef Derived super; // Creates an alias for Derived
void DerivedDerived::bar() { super::bar(); // Calls Derived::bar super::super::bar; // Calls Base::bar }
Benefits
The "typedef super" idiom offers several benefits:
Commonality and Standardization
While the "typedef super" idiom has become fairly common, it is still considered a non-standard feature in C . However, the discussion mentioned in the answer suggests that the concept was initially considered for inclusion in the language.
Conclusion
The "typedef super" idiom is a useful technique that enhances code readability and consistency within C programs. It is widely used and has been implemented by programmers to emulate the functionality of the "super" keyword found in other languages. Although not standardized, this idiom remains a valuable tool for experienced C developers.
The above is the detailed content of Why is the 'typedef super' idiom so commonly used in C ?. For more information, please follow other related articles on the PHP Chinese website!