Home > Article > Backend Development > How to Access Protected Member Variables in Inherited Classes in C Templates?
Templates: Visibility of Parent Class Member Variables in Inherited Class
In C templates, member variables of a parent class may not be visible in inherited classes by default. This can lead to compilation errors when accessing these variables.
Consider the following example:
<code class="cpp">template <class elemType> class arrayListType { protected: elemType *list; int length; }; template <class elemType> class unorderedArrayListType: public arrayListType<elemType> { void insertAt(int, const elemType&); // Function that uses 'list' and 'length' };</code>
In the inherited class unorderedArrayListType, accessing the protected variables list and length directly will result in errors such as "'length' was not declared in this scope'". To resolve this issue, we need to explicitly declare these variables within the derived class.
There are two main approaches to do this:
Use "this->" Prefix:
Prefix each member variable with this->, e.g.:
<code class="cpp">void insertAt(int location, const elemType& insertItem) { for (int i = this->length; i > location; i--) this->list[i] = this->list[i - 1]; this->list[location] = insertItem; this->length++; }</code>
Use Declarations:
Include declarations for the member variables in the private section of the derived class, e.g.:
<code class="cpp">class unorderedArrayListType: public arrayListType<elemType> { private: using arrayListType<elemType>::length; // Declare 'length' explicitly using arrayListType<elemType>::list; // Declare 'list' explicitly public: void insertAt(int, const elemType&); };</code>
The above is the detailed content of How to Access Protected Member Variables in Inherited Classes in C Templates?. For more information, please follow other related articles on the PHP Chinese website!