3

Can someone please enlighten me on why this-> is required to access a parent class member variable in this scenario?

template <int S>
class A
{
protected:
    int x[S];
};

template <int S>
class B : public A<S>
{
    void Initialise()
    {
        this->x[0] = 0; // OK
        x[0] = 0;       // error: 'x' was not declared in this scope
    }
};

Thanks in advance...

EDIT:

This compiles OK:

template <int S>
class A
{
protected:
    int x[S];
};

class B : public A<5>
{
    void Initialise()
    {
        this->x[0] = 0; // OK
        x[0] = 0;       // OK
    }
};
Ashley Duncan
  • 825
  • 1
  • 8
  • 22
  • fyi `B::x[0] = 0;` also works ... investigating. – Richard Critten Jun 05 '19 at 21:57
  • Seeing the edit it looks like B isn't fully defined at the point where you try to access it (because B is a template), although it should (because we are in a function definition). Is there a language lawyer around that can clarify this? – Timo Jun 05 '19 at 22:06
  • @Timo - But if you move the definition B::Initialise out of line it still fails same error. – davidbak Jun 05 '19 at 22:08
  • That's because `A` is nothing until `S` is known, so you must qualify the name to ensure it's a member of parent class. – Jack Jun 05 '19 at 22:11
  • @davidbak that's what I'm saying. It looks like B isn't fully defined but it should be inside a function definition, no matter if inside or outside the class definition. – Timo Jun 05 '19 at 22:11
  • @Jack, correct because `A::x[0] = 0` does work! – davidbak Jun 05 '19 at 22:12
  • Thanks everyone for your help and the suggestion of the duplicate post. And I searched so hard for an answer too and didn't find it. Must have been googling it all wrong! – Ashley Duncan Jun 05 '19 at 22:12
  • @Timo - ah, didn't know that "fully defined" didn't depend on seeing the "whole" decl in some way (thus that defining the method out-of-line wouldn't make a difference) – davidbak Jun 05 '19 at 22:13
  • And in the second example, base class `A<5>` is not a dependent type, so its members can be seen for lookup. – aschepler Jun 05 '19 at 22:13

0 Answers0