While this is not actually a problem, it confuses the hell out of me.
In the following code, I cannot access a member of my base class in my derived class, without using the this
pointer.
Can someone point me to the rule that forces me to use the this
pointer here?
I tested it with gcc 8.2 and intel 18.0.2, as I first assumed it must be some compiler bug. But both compilers complain, so I guess its something I'm missing here? You can just copy/paste this code to http://www.onlinegdb.com to test it out.
#include <iostream>
template <typename T, typename U>
class MyClassBase {
public:
MyClassBase()
: somebool(true) {
};
virtual ~MyClassBase() {};
virtual void someMethod()=0;
protected:
bool somebool;
};
template<typename T, typename U>
class MyClass : public MyClassBase<T, U> {
public:
MyClass() : MyClassBase<T, U>() {};
void someMethod() override;
};
template <typename T>
class MyClass<T, std::string> : public MyClassBase<T, std::string> {
public:
MyClass() : MyClassBase<T, std::string>() {};
void someMethod() override;
};
//implementation generic class
template <typename T, typename U>
void MyClass<T, U>::someMethod() {
std::cout << "Generic: " << this->somebool << std::endl; //works
std::cout << "Generic: " << somebool << std::endl; //fails to compile
}
//implementation specialization
template <typename T>
void MyClass<T, std::string>::someMethod() {
std::cout << "Specialized: " << this->somebool << std::endl; //works
std::cout << "Specialized: " << somebool << std::endl; //fails to compile
}
int main()
{
MyClass<int, int> class_generic;
MyClass<int, std::string> class_specialized;
class_generic.someMethod();
class_specialized.someMethod();
return 0;
}
The error I get is that the base class member is unknown.
main.cpp: In member function ‘void MyClass<T, U>::someMethod()’:
main.cpp:41:33: error: ‘somebool’ was not declared in this scope
std::cout << "Generic: " << somebool << std::endl;
^
main.cpp: In member function ‘void MyClass<T, std::basic_string<char> >::someMethod()’:
main.cpp:47:37: error: ‘somebool’ was not declared in this scope
std::cout << "Specialized: " << somebool << std::endl;
^