I was playing with templates and decided to make an abstract class template(AbstractOperation) with protected data members. Now I inherit them publically to Addition but when I try to access the protected data members of base class directly inside a member function of derived class it fails to compile ie return mLhs + mRhs;
, but return this->mLhs +this->mRhs;
works fine in int Addition<oprand>::operation()
.
So I repeated the same class hierarchy without templates now I can access the members just fine.class A
and class B
, int fun() { return m; }
So what I'm trying to understand is why compilation fails for the line return mLhs + mRhs;
Below is my sample code , online link
#include <iostream>
// template implementation
template <typename oprand>
class AbstractOperation
{
protected:
oprand mLhs;
oprand mRhs;
public:
virtual int operation() = 0;
AbstractOperation(oprand x, oprand y) : mLhs(x), mRhs(y) {}
oprand getLhs() const { return mLhs; }
oprand getRhs() const { return mRhs; }
};
template <typename oprand>
class Addition : public AbstractOperation<oprand>
{
public:
Addition(oprand x, oprand y) : AbstractOperation<oprand>(x, y) {}
int operation();
};
template <typename oprand>
int Addition<oprand>::operation()
{
return mLhs + mRhs; // fails to compile
// return this->mLhs +this->mRhs; // compile successfully
// return AbstractOperation<oprand>::mLhs + AbstractOperation<oprand>::mRhs; //compile successfully
}
// normal implementation
class A
{
protected:
int m;
public:
A(int val) : m(val) {}
virtual int fun() = 0;
};
class B : public A
{
public:
B(int val) : A(val) {}
int fun() { return m; }
};
int main()
{
A *a = new B(5);
std::cout << a->fun() << "\n";
AbstractOperation<int> *p = new Addition<int>(4, 5);
std::cout << p->operation() << "\n";
delete a;
delete p;
}
Error
main.cpp: In member function ‘int Addition<oprand>::operation()’:
main.cpp:28:12: error: ‘mLhs’ was not declared in this scope
return mLhs + mRhs; // fails to compile
^~~~
main.cpp:28:19: error: ‘mRhs’ was not declared in this scope
return mLhs + mRhs; // fails to compile
^~~~