Protected member is "not declared in this scope" in derived class
16,954
Solution 1
To fix this, you need to specify Base<T>::data_.clear()
or this->data_.clear()
. As for why this happens, see here.
Solution 2
In the case of templates compiler is not able to determine if the member is really coming from base class. So use this
pointer and it should work:
void clear()
{
this->data_.clear();
}
When compiler looks the Derived class definition, it doesn't know which Base<T>
is being inherited (as T
is unknown). Also data_
is not any of the template
parameter or globally visible variable. Thus compiler complains about it.
Comments
-
Martin Drozdik about 2 years
#include <vector> #include <iostream> template <class T> class Base { protected: std::vector<T> data_; }; template <class T> class Derived : public Base<T> { public: void clear() { data_.clear(); } }; int main(int argc, char *argv[]) { Derived<int> derived; derived.clear(); return 0; }
I cannot compile this program. I get:
main.cpp:22: error: 'data_' was not declared in this scope
Please, could you explain why
data_
is not visible in theDerived
class?