4

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
  • 45,211
  • 10
  • 74
  • 119

1 Answers1

14

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
  • 369,052
  • 73
  • 620
  • 1,021