I'm looking for an elegant solution to the following "problem":
Consider the classes Base and Child, and the way operator+ works here:
class Base
{
public:
Base(int a=0) : mValue(a) {};
Base(const Base& rhs) : mValue(rhs.mValue) {};
Base& operator=(const Base& rhs) {
if (this==&rhs) return *this;
mValue=rhs.mValue;
}
friend const Base operator+(Base &lhs, Base &rhs);
private:
int mValue;
};
const Base operator+(Base &lhs, Base &rhs)
{
Base result(lhs.mValue+rhs.mValue);
return result;
}
class Child : public Base
{
public:
Child(int a=0) : Base(a) {};
};
int main()
{
Child a(2);
Child b(5);
Child c(a+b); // **** This line ****
Child d;
d=(a+b); // **** or this other one ****
}
The marked lines in main give the error: cannot convert from 'const Base' to 'Child'
I understand perfectly that the operator has been defined in the Base class, and returns an object of type Base, which can't be converted to Child. One solution is overloading operator+ for the Child class, but I am wondering whether there is a better, less costly method. I'm under the impression that I'm forgetting a much easier option. Thanks!