I am new to C++. During my learning phase I encountered with below issue.
I am trying to derive a class stack
from a class template Queue
.
Compiler thr
The reason is that inside a template, two-phase name lookup rules apply:
Names which do not depend on template parameters are looked up (=resolved) when the template is defined (=parsed).
Names which do depend on template parameters are looked up when the template is instantiated (when you provide the template arguments).
Base classes which depend on template parameters are only searched during name lookup at instantiation time.
The reason for this two-phase lookup is that until the template arguments are known, the compiler cannot know what the definition of the base class (or other dependent construct) will be. Remember that template specialisation exists.
You need to somehow tell the compiler that the name b
is dependent. You basically have three ways to do that:
Prefix the name with this->
; since you're in a class template, all your members depend on template parameters implicitly:
this->b = a;
Use full qualification for the name. This will make the dependency on template parameters explicit:
Queue::b = a;
Put a using
declaration into your class to inform the compiler that the name comes from a dependent base class:
template
class stack :public Queue // Derived class
{
protected:
using Queue::b;
public:
stack():Queue()
{
b=a;
}
void pop()
{
b--;
}
};