3

OS :Windows 8.1

Compiler: GNU C++

I have two template classes: base and derived. In the base class I declare variable value. When I try apply to value from a method of derived class the compiler reports an error to me. But if I do not use templates I do not get an error message.

There is the error message:

main.cpp: In member function 'void Second<T>::setValue(const T&)':
main.cpp:17:3: error: 'value' was not declared in this scope
   value = val;
   ^

There is the code:

#include <iostream>

using namespace std;

template<class T>
class First {
public:
    T value;
    First() {}
};

template<class T>
class Second : public First<T> {
    public:
    Second() {}
    void setValue(const T& val) {
        value = val;
    }
};

int main() {
    Second<int> x;
    x.setValue(10);
    cout << x.value << endl;
    return 0;
}

This code is work:

#include <iostream>

using namespace std;

class First {
public:
    int value;
    First() {}
};

class Second : public First {
public:
    Second() {}
    void setValue(const int& val) {
        value = val;
    }
};

int main() {
    Second x;
    x.setValue(10);
    cout << x.value << endl;
    return 0;
}
Good
  • 306
  • 1
  • 17

1 Answers1

6

Because the base class is dependent, that is, dependent on your template parameter T. In those cases, unqualified name lookup does not consider the scope of the base class. So you must qualify the name, with, for example, this.

this->value = val;

Please note that MSVC is not compliant with this rule and will resolve the name even if it is unqualified.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434