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

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

Mary-Kate Olsen
Release: 2024-12-06 20:16:12
Original
584 people have browsed it

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

Accessing Inherited Variables from Templated Parent Class

The code snippet provided illustrates a scenario where the inherited class Bar attempts to access protected variables of its parent class Foo, which is a templated class. However, the compiler generates errors, leading to confusion regarding whether the compiler adheres to the standard.

According to the C standard, unqualified names within a template are considered non-dependent and must be resolved when the template is defined. Since the specialized base class templates may not be available during the template definition, unresolved unqualified names result in errors.

This applies to both variables and functions declared in the base class, as seen in the example where Bar can access a using qualified names or using declarations. The latter allows unqualified access within the derived class, resolving the initial error.

For instance, the following code modifications resolve the issue:

template<class T>
int Bar<T>::Perna(int u) {
  int c = Foo<T>::a * 4;  // Qualified name
  c = this->a * 4;        // Pointer to own instance
  using Foo<T>::a;
  c = a * 4;               // Using declaration
}
Copy after login

By clarifying the lookup rules and providing alternative solutions, this explanation underscores the nuances of template resolution and helps developers understand the rationale behind the compiler's behavior.

The above is the detailed content of How Can Inherited Classes Access Protected 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