Thursday, January 25, 2007

Inheritance appears to break when deriving a template class

If you have a base template class from which you derive another template class inheritance can appear to break, i.e. you don't appear to be able to access the base classes variables and methods directly. For example take the following code:


#include <iostream>

template <class _prec> class Base {
public:
_prec i;

Base() {
i = 12;
}

virtual void f() {
std::cout << i << std::endl;
}

};

template <class _prec> class Derived : public Base<_prec> {
public:
void f() {
std::cout << i*2 << std::endl;
}
};

int main() {
Base<int> b;
Derived<int> d;

b.f();
d.f();

return 0;
}



On gcc 4.1.2 this gives the following error:

derive_test.cpp: In member function ‘void Derived<_prec>::f()’:
derive_test.cpp:20: error: ‘i’ was not declared in this scope



The problem is caused because the base class is not in scope, why I find unclear, and the work around a little messy. But basically if you change
std::cout << i*2 << std::endl;
to
std::cout << this->i*2 << std::endl;

All will be well.


More info at: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19 and
http://gcc.gnu.org/onlinedocs/gcc/Name-lookup.html

No comments: