I want to implement some hierarchy of classes with polymorphism and I can't make it to work. I have two problems:
- The Derived class has extra private variables
- The methods of the derived class take as argument an object of the derived class and return an object of the derived class.
I can make this code work, but in a non-polymorphic way. This is the simplified version:
class Base
{
protected:
int mInt;
public:
Base(int iValue) : mInt(iValue) {}
virtual Base operator+(const Base otherBase)
{
Base result( otherBase.mInt + mInt);
return result;
}
};
class Derived : public Base
{
private:
double mDouble;
public:
Derived(int iValue, double dValue) : Base(iValue)
{
mDouble = dValue;
}
Derived operator+(const Derived otherDerived)
{
Derived result(otherDerived.mInt + mInt,
otherDerived.mDouble + mDouble);
return result;
}
};
int main()
{
Derived DobjectA(2,6.3);
Derived DobjectB(5,3.1);
Base* pBaseA = &DobjectA;
Base* pBaseB = &DobjectB;
// This does not work
Derived DobjectC = (*pBaseA)+(*pBaseB);
}
How can I design the classes to make this work?