Home c++ Error: 'a' was not declared in this scope

Error: ‘a’ was not declared in this scope




I downloaded the latest qt 5.3.0 from MinGW 4.8.2 and was surprised. (same with qt 5.2.0 with MinGW 4.8.0)

# include & lt; iostream & gt;
using namespace std;
template & lt; typename T & gt;
class Super {
  class A {
    int a;
  class B: public A {
    int b;
    B () {
      b = a;
int main ()
  cout & lt; & lt; "Hello World!" & lt; & lt; endl;
  return 0;

Doesn’t work. Produces:

C: \ *** \ main.cpp: 14: error: 'a' was not declared in this scope
       b = a;

Although, remove the line template & lt; typename T & gt; , everything works.

Answer 1, authority 100%

I think I get it. Here discusses a similar issue.

In your case, the situation is as follows. b is a dependent name . The compiler must understand the meaning of this dependent name before the substitution T . (See this question for details and discussion). Since it cannot, the developers of the standard decided to remove dependent names from scope within the template. Therefore, you have to specify explicitly what you want.

Thus, a bug in the old Visual Studio, their implementation did not fully comply with the standards. (Already compliant in new Visual Studio.)

I find C++ to be unnecessarily complicated. You stumbled upon one of these places.

Answer 2, authority 20%

When performing an unqualified name lookup, the base classes that depend on the parameters of the current template are not included. In this case, A is actually Super & lt; T & gt; :: A and depends on the template parameter T . For this reason, the name a from the base class A is not found by the compiler.

Using qualified name or explicit class member access syntax will fix the error

int b = A :: a;
int b = this- & gt; a;

This rule deals with the search for unqualified names in base classes , and not with dependent names in general. This detail is somehow not covered in the accepted answer.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions