5

I want to access protected variable in parent class, I have the following code and it compiles fine:

class Base
{
protected:
    int a;
};

class Child : protected Base
{
public:
    int b;
    void foo(){
        b = a;
    }
};

int main() {
    Child c;
    c.foo();
}

Ok, now I want to make everything templated. I changed code to the following

template<typename T>
class Base
{
protected:
    int a;
};

template <typename T>
class Child : protected Base<T>
{
public:
    int b;
    void foo(){
        b = a;
    }
};

int main() {
    Child<int> c;
    c.foo();
}

And got error:

test.cpp: In member function ‘void Child<T>::foo()’:
test.cpp:14:17: error: ‘a’ was not declared in this scope
             b = a;
                 ^

Is it correct behavior? What's the difference?

I use g++ 4.9.1

RiaD
  • 46,822
  • 11
  • 79
  • 123

1 Answers1

17

Hehe, my favourite C++ oddity!

This will work:

void foo()
{
   b = this->a;
//     ^^^^^^
}

Unqualified lookup doesn't work here because the base is a template. That's just the way it is, and comes down to highly technical details about how C++ programs are translated.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055