Parent Class Member Variables Not Visible in Inherited Class
When inheriting a class as a template, protected variables of the parent class may not be visible in the inherited class. This can lead to compile errors when accessing those variables in the inherited class.
Consider the following example:
<code class="cpp">// Parent class template <class elemType> class arrayListType { protected: elemType *list; int length; // ... }; // Inherited class template <class elemType> class unorderedArrayListType: public arrayListType<elemType> { public: void insertAt(int location, const elemType& insertItem); // ... };</code>
When the compiler encounters the unorderedArrayListType class, it attempts to validate the insertAt function. However, it cannot find the length and list variables declared in the arrayListType class. This results in compile errors.
Solution
To resolve this issue, there are two possible solutions:
1. Prefix with this->
Prefixing the inherited variables with this-> explicitly specifies that they belong to the parent class:
<code class="cpp">// Inherited class template <class elemType> class unorderedArrayListType: public arrayListType<elemType> { public: void insertAt(int location, const elemType& insertItem) { this->length++; // ... } // ... };</code>
2. Use Declarations
Declaring the inherited variables in the private section of the inherited class:
<code class="cpp">// Inherited class template <class elemType> class unorderedArrayListType: public arrayListType<elemType> { private: using arrayListType<elemType>::length; using arrayListType<elemType>::list; public: void insertAt(int location, const elemType& insertItem) { length++; // ... } // ... };</code>
Both methods ensure that the compiler explicitly understands that the inherited variables come from the parent class.
The above is the detailed content of Why Can't I Access Parent Class Member Variables in My Inherited Class?. For more information, please follow other related articles on the PHP Chinese website!