i am a new programmer in c++. and i am using templates for the first time.
i have an abstract class and another class extending it. but all the protected members of the abstract class are not recognised by the other class:
class0.h:
template<class T>
class class0 {
protected:
char p;
public:
char getChar();
};
**class1.h**
template<class T>
class class1:public class0<T> {
public:
void printChar();
};
template<class T>
void class1<T>::printChar(){
cout<< p<<endl;//p was not declared in this scope
}
thank you. have a great week =)
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.
The main type of templates that can be implemented in C are static templates. Static templates are created at compile time and do not perform runtime checks on sizes, because they shift that responsibility to the compiler.
Template class. is an instance of a class template. A template definition is identical to any valid class definition that the template might generate, except for the following: The class template definition is preceded by template< template-parameter-list >
A class template is a template that is used to generate classes whereas a template class is a class that is produced by a template.
The reason that this is happening is to do with the lookup rules for templates.
p
isn't a dependent expression because it is just an identifier and not something that depends on the template parameter. This means that base classes that are dependent on the template parameter won't be searched to resolve the name p
. To work around this issue you need to use something that does depend on the template parameter. Using this->
will do this.
e.g.
cout << this->p << endl;
For a name to be looked up in a dependent base class, two conditions need to be satisfied
These rules as stated in C++03 are different from the rules stated by unrevised C++98, where satisfying the second bullet (making a name dependent) was sufficient for finding names declared in dependent base classes.
A dependent name is looked up at instantiation time and a lookup other than unqualified lookup will not ignore dependent base classes. Both of these conditions need to be satisfied to find a name declared in a dependent base class, neither of them alone is sufficient. To satisfy both conditions you can use various constructs
this->p
class1::p
Both names p
are dependent and the first version uses class member access lookup and the second version uses qualified name lookup.
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