Home > Backend Development > C++ > How Can I Access Protected Inherited Variables in Templated Parent Classes in C ?

How Can I Access Protected Inherited Variables in Templated Parent Classes in C ?

Patricia Arquette
Release: 2024-12-10 07:56:12
Original
413 people have browsed it

How Can I Access Protected Inherited Variables in Templated Parent Classes in C  ?

Accessing Inherited Protected Variables in Templated Parent Classes

The issue arises when attempting to access protected inherited variables from templated parent classes in C . Consider the following C code:

template<class T> class Foo {
    protected:
        int a;
};

template<class T> class Bar : public Foo<T> {
    protected:
        int b;
};

template<class T> int Bar<T>::Perna(int u) {
    int c = Foo<T>::a * 4; // This works
    return (a + b) * u;    // This doesn't
}
Copy after login

In this case, GCC versions 3.4.6 and newer raise an error when attempting to access the protected variable a of the inherited Foo class. Older compilers, including GCC 2.96 and MSVC 6-9, allow this access without issue.

Error Explanation

The error occurs because, according to the C standard, unqualified names in templates must be looked up during template definition. However, the definition of a dependent base class (such as Foo in this case) may not be known at the time of template definition. This uncertainty prevents the resolution of unqualified names.

Standard Compliance

The behavior exhibited by GCC 3.4.6 and later versions is in compliance with the C standard. By adhering to the standard, these compilers ensure that code correctness and behavior are consistent across different platforms and compilers.

Resolution

To resolve this issue and access the protected inherited variable, one can either use the qualified name of the variable (e.g., Foo::a) or utilize a "using" declaration. For example:

template<class T>
int Bar<T>::Perna(int u) {
    int c = this->a * 4; // Access using the qualified name
    c = a * 4;          // Access using the "using" declaration
}
Copy after login

In this modified code, the qualified name or "using" declaration explicitly specifies the source of the a variable, allowing the compiler to resolve it correctly.

The above is the detailed content of How Can I Access Protected Inherited Variables in Templated Parent Classes in C ?. 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