Home > Article > Backend Development > Why Are Base Class Identifiers Inaccessible in Derived Template Classes in C ?
Limited Identifier Visibility in Derived Template Classes
In C , template classes introduce a unique aspect in inheritance: identifiers defined in a base template class may not be visible to derived template classes. This behavior, known as two-phase lookup, arises due to the different stages involved in template instantiation and compilation.
Consider the following example:
template <typename T> class Base { public: static const bool ZEROFILL = true; static const bool NO_ZEROFILL = false; }; template <typename T> class Derived : public Base<T> { public: Derived(bool initZero = NO_ZEROFILL); // NO_ZEROFILL is not visible ~Derived(); };
When compiling this code, GCC g 3.4.4 (cygwin) produces an error, as Derived cannot access NO_ZEROFILL from its base class Base. This is because during the first phase of template instantiation, when the compiler parses the code, it does not have a concrete type assigned to T. As a result, it cannot determine the specific Base class that Derived inherits from and therefore cannot resolve identifiers defined within the base class.
To overcome this limitation, explicit qualification is required when accessing base class identifiers in derived template classes. The code below addresses the issue:
template <typename T> class Derived : public Base<T> { public: Derived(bool initZero = Base<T>::NO_ZEROFILL); // Explicit qualification ~Derived(); };
By using Base
Thus, in derived template classes, identifiers defined in base template classes are only accessible with explicit qualification, ensuring correct resolution at run-time when the template is instantiated with specific types.
The above is the detailed content of Why Are Base Class Identifiers Inaccessible in Derived Template Classes in C ?. For more information, please follow other related articles on the PHP Chinese website!