I read many disscussions about operator overloading and inheritance, however there is still a point about operator overloading in child classes. My case is specific to binary arithmetic operators like *, +, - and also operators as member functions.
What is the proper way to overload an arithmetic operator in the derived class which inherits from a base class which also overload the same operator. For ex: we can call the base (copy) constructors for the parent class(es) in the derived classes in order to delegate the task to the parent(s) which can handle this task. However, I did not see something similar to this approach for these operators.
Can/Should I do all the tasks in the derived class (for ex: add or substract the members of the base class also), or somehow delegate these tasks to the base class which owns the members under consideration (or is it possible/feasible to do that?).
I have a very small and simple code in order to test this case. I have a base class named 'OpBase' and of course a derived (from Opbase) class 'OpDerived'. Both declare/define a member variable (int type). In this case, I multiply both the Base and Derived class members in the operator overload in the Derived class. What is the proper to go in that case? This question may not have an absolute answer, but doing everything in Derived class(es) seems to be a bit problematic for maintainability issues.
class OpBase
{
protected:
int last;
explicit OpBase() { last = 1; }
explicit OpBase(int la) { this->last = la; }
OpBase operator*(const OpBase &rhs) {
OpBase op;
op.last *= rhs.last;
return op;
}
};
class OpDerived: public OpBase
{
public:
int first;
explicit OpDerived(): first(1) { }
OpDerived operator*(const OpDerived &rhs) {
OpDerived op;
op.first *= rhs.first;
op.last *= rhs.last;
return op;
}
OpDerived(const OpDerived &rhs):OpBase(rhs) {
this->first = rhs.first;
}
};