3

I'm trying to figure out, how can I inherit from template class to template class. The problem is: I can't use protected members of Parent class.

Example:

template <class N>
class Parent {
protected:
    N member;
public:
    Parent(N aa){
        member = aa;
    }
};


class Child1: public Parent<int>{
    public:
        Child1(int a): Parent<int>(a) {
            member += 1; // works
        }
};

template<class Q>
class Child2: public Parent<Q>{
    public:
        Child2(int a): Parent<Q>(a) {
            member += 1; // does not work (use of undeclared identifier)
        }
};

How can I use "member" in the Child2 class?

Thanks for your time

eightlay
  • 423
  • 2
  • 9
  • 1
    `this->member` will work. [This question](https://stackoverflow.com/questions/30245777/access-static-member-of-template-parent-class) explains it, though the origin was about static members the reason is still the same, and includes links to additional explanations. – WhozCraig Jan 23 '22 at 22:55

1 Answers1

3

You need to use this->member or Parent<Q>::member.

In the second case, member is a "dependent name" because the existence of member from the base class template Parent<Q> depends on the type of class Q in the template, whereas in the first example there is no dependent type, the compiler can statically analyze that Parent<int> contains member.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153