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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With