Home > Backend Development > C++ > Why Can\'t I Access Parent Class Member Variables in My Inherited Class?

Why Can\'t I Access Parent Class Member Variables in My Inherited Class?

DDD
Release: 2024-11-01 01:03:28
Original
502 people have browsed it

Why Can't I Access Parent Class Member Variables in My Inherited Class?

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&amp; insertItem);
    // ...
};</code>
Copy after login

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&amp; insertItem) {
        this->length++;
        // ...
    }
    // ...
};</code>
Copy after login

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&amp; insertItem) {
        length++;
        // ...
    }
    // ...
};</code>
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template