I require some clarification on the question why do we need the scope resolution operator or this
pointer to access publicly inherited members from a template base class.
As I understand it is for adding clarity but then how does this
add any further clarity than just point that it is a member of the class.
To make my question clearer I have added some code.
#include <iostream>
using namespace std;
template <class T, class A>
class mypair {
public:
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
virtual void printA()
{
cout<<"A"<<a<<endl;
cout<<"B"<<b<<endl;
}
};
template <class T, class A>
class next: mypair<T,A>
{
public:
next (T first, T second) : mypair<T,A>(first, second)
{
}
void printA()
{
cout<<"A:"<<mypair<T,A>::a<<endl; // this->a; also works
cout<<"B:"<<mypair<T,A>::b<<endl; // this-b; also works
}
};
int main () {
next<double,float> newobject(100.25, 75.77);
newobject.printA();
return 0;
}
Output:
A:100.25
B:75.77
If i remove the scope(or this operator) then the out of scope error comes. But why do we need a scope for publicly inherited members.
Some thoughts on this would be great.
Refer to Name lookup - Using the GNU Compiler Collection (GCC)
By adding explicit prefix mypair<T, A>
, or this->
, you make printA
template argument dependent. Then the definitions will be resolved during template instantiation stage.
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