4

Why would the following work just fine:

class a
{
   public:
    int n;
};

class b : public a
{
 public:
  b()
  {
      n = 1;
  }
};

int main()
{
}

but this does not work:

template <class T>
class a
{
   public:
      int n;
};

template <class T>
class b : public a<T>
{
   public:
    b()
    {
       n = 1;
    }
};

int main()
{
}

and gives the following error:

 1.cpp: In constructor ā€˜b<T>::b()’:
 1.cpp:14: error: ā€˜n’ was not declared in this scope

and how would one inherit a template class while being able to use its base members and keep the type generic?

kloop
  • 4,537
  • 13
  • 42
  • 66

1 Answers1

3

You need to qualify it with "this" or with a "using" directive (or explicitly with the base class qualification).

In a nutshell: that variable is a nondependent type (non-dependent on the T of the template class), the compiler doesn't look into a dependent type (your a< T >) when looking for declarations for a nondependent type.

this->n, since "this" refers to a dependent class, works. The same with the other methods I listed.


References:

Faq here: http://www.parashift.com/c++-faq-lite/nondependent-name-lookup-members.html Live example here: http://ideone.com/nsw4XJ

Marco A.
  • 43,032
  • 26
  • 132
  • 246