A coworker asked me today about code which looks somewhat like this:
#include <iostream>
template <class T>
class IBase {
public:
virtual ~IBase() {}
public:
virtual void foo() = 0;
};
template <class T>
class Base : public IBase<T> {
public:
virtual void bar() {
foo(); // compiler error
}
};
class Derived : public Base<int> {
public:
virtual void foo() {
std::cout << "Hello World!\n";
}
};
int main() {
Derived d;
d.bar();
}
At first he was getting a compiler error saying that "foo()
" was not found. OK, so he tried to change it to IBase<T>::foo();
. While that compiled, it resulting in a linker error. So immediately, I recalled that I've seen this type of problem before and suggesting that he write this->foo();
instead. Viola! problem solved!
Then he asked me why didn't plain foo();
work? Isn't this->x();
essentially the same as x();
? Honestly, I have no idea, but he piqued my interest. So here we are:
In summary:
virtual void bar() {
this->foo(); // works
//IBase<T>::foo(); // linker error
//foo(); // compiler error
}
The question is why is this->
required. And why won't the other options work?