0

What am I doing wrong in this code?

template <typename T>
class CLASS1
{
public:
    T member;
};

template <typename T>
class CLASS2 : public CLASS1<T>
{public:
    void func()
    {

        member = 4;
    }
};

Visual Studio error:

member identifier not found

G++ error:

‘member’ was not declared in this scope

Zebrafish
  • 11,682
  • 3
  • 43
  • 119
  • Keep in mind that a class template can have different sets of members for each template argument. There's no guarantee that a specialization won't cause `member` to go missing. At the same time, there's nothing in your code suggesting that the name `member` needs to have its lookup delayed until the template argument is known. – chris May 25 '20 at 17:58

1 Answers1

1

You need to specify where the name member comes from. In this case, it comes from the inherited class template CLASS1<T>, so you need to say:

void func()
{
  CLASS1<T>::member = 4;
}

If you say this->member, then the compiler knows to look for names in the base classes as well. So you could do:

void func()
{
  this->member = 4;
}
cigien
  • 57,834
  • 11
  • 73
  • 112
  • `this->member` also works. – HolyBlackCat May 25 '20 at 17:53
  • @HolyBlackCat True, added that to the answer. – cigien May 25 '20 at 17:55
  • Wow thank you. @HolyBlackCat 'this' seems a lot cleaner. What's the reasoning needing a qualified name with template classes? – Zebrafish May 25 '20 at 17:55
  • See the linked dupe, it has an explanation of this. When inheriting from class templates, the compiler needs some help to tell it where to look for names. – cigien May 25 '20 at 17:57
  • @Zebrafish IIRC, that's because the base class could be specialized to not have `member` in it. If accessing `member` directly was allowed, then determining whether it actually referes to a class member or to some global entity would have to be done when instantiating the template (rather than when seeing it for the first time), which would be annoying and error-prone. – HolyBlackCat May 25 '20 at 18:03