9

Possible Duplicate:
Why do I have to access template base class members through the this pointer?

I have a class hierarchy like the following:

template<typename T>
class Base {
protected:
    T t;
};

template<typename T>
class Derived: public Base<T> {
public:
    T get() { return t; }
};

int main() {
    Derived<int> d;
    d.get();
}

The problem is that the protected member variable t is not found in the Base class. Compiler output:

prog.cpp: In member function 'T Derived<T>::get()':
prog.cpp:10:22: error: 't' was not declared in this scope

Is that correct compiler behavior or just a compiler bug? If it is correct, why is it so? What is the best workaround?

Using fully qualified name works, but it seems to be unnecessarily verbose:

T get() { return Base<T>::t; }
Community
  • 1
  • 1
Juraj Blaho
  • 13,301
  • 7
  • 50
  • 96

1 Answers1

9

To use members from template base classes, you have to prefix with this->.

template<typename T>
class Derived: public Base<T> {
public:
    T get() { return this->t; }
};
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510