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;
}