Home > Backend Development > C++ > How to Access Protected Member Variables in Inherited Classes in C Templates?

How to Access Protected Member Variables in Inherited Classes in C Templates?

Mary-Kate Olsen
Release: 2024-10-30 09:23:03
Original
986 people have browsed it

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>
Copy after login

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:

  1. 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>
    Copy after login
  2. 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>
    Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template