1

I'm having issues with accessing protected members in template subclasses of a template class.

Thing is, if I remove the templates, everything works fine. I know how to work around my problem in an ugly way, by simply writing "using Base::my_protected_member" for every single derived class. But why should I need to do that in the first place ?

Here's a minimal commented example

template<class T>
class Base
{
    protected:
        T x;
    public:
        Base(T x) : x(x) {}
};

template<class T>
class Derived : public Base<T>
{
    //using Base<T>::x; //why ?!

    public:
        Derived(T x);
        void print();
};

template<class T>
Derived<T>::Derived(T x) : Base<T>(x) 
{ cout << x << endl; } //works fine

template<class T>
void Derived<T>::print() { cout << x << endl; } //doesn't work

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

I don't quite understand what's going on, or how to work around this in a nice way. probably I'm doing something wrong...

R. Absil
  • 173
  • 6
  • 1
    Note that in the constructor you actually use the paramter `x`, not the inherited member. – Igor R. May 11 '19 at 08:09
  • yeah, my bad. But why I can't elsewhere since it's protected ? – R. Absil May 11 '19 at 10:07
  • No, even it it were public in the base, you'd have the same issue. See the related answers. – Igor R. May 11 '19 at 16:40
  • yeah, couldn't find related topics while searching, but the post is clearly duplicate. Basically : you hav to explicitely specify this->mymember in order to make the name dependent. – R. Absil May 12 '19 at 17:27

0 Answers0