Possible Duplicates:
[FAQ] Why doesn't a derived template class have access to a base template class' identifiers? Problem with protected fields in base class in c++
cannot access data member in a class template
Following code gives me compilation error. What is wrong?
struct Base {
int amount;
};
template<class T> struct D1 : public Base {
};
template<class T>
struct D2 : D1<T> {
void foo() { amount=amount*2; /* I am trying to access base class data member */ };
};
int main() {
D2<int> data;
};
test.cpp: In member function 'void D2<T>::foo()':
test.cpp:11: error: 'amount' was not declared in this scope
How to fix this?
thanks
Inherited Member Functions of Class Templates are not Available.
It is possible to inherit from a template class. All the usual rules for inheritance and polymorphism apply. If we want the new, derived class to be generic it should also be a template class; and pass its template parameter along to the base class.
There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.
The "diamond problem" (sometimes referred to as the "Deadly Diamond of Death") is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C.
The problem here has to do with how names are looked up in template classes that inherit from template base classes. The actual rules behind it are pretty arcane and I don't know them off the top of my head; I usually have to consult a reference to learn precisely why this doesn't work.
The way to fix this is to explicitly prefix the member you're accessing with this->
:
void foo() {
this->amount = this->amount * 2; // Or: this->amount *= 2;
}
This gives the compiler an unambiguous hint about where the name amount
comes from and should resolve the compiler error.
If someone wants to give a more detailed description of why this error occurs I'd love to see a good explanation.
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