Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access variable in template base class [duplicate]

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

like image 827
RiaD Avatar asked Dec 10 '22 22:12

RiaD


1 Answers

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.

like image 65
Lightness Races in Orbit Avatar answered Feb 16 '23 05:02

Lightness Races in Orbit