The code that I am having trouble with is this line:
result.addElement(&(*(setArray[i]) + *(rhs.setArray[j])));
The + operator in my class is overloaded like this (there are a variety of overloads that can fit in this set, but they all have a similar header):
const Rational Rational::operator+(const Rational &rhs) const
The setarrays in the code above are both arrays of pointers, but the + operator requires references, which might be the problem.
AddElement, the method of result, has this header:
bool Set::addElement(Multinumber* newElement)
The Multinumber* in the header is the parent class of Rational, mentioned above. I don’t think any of the specific code matters. I’m pretty sure that it is a syntax issue.
My compiler error is:
68: error: invalid conversion from 'const Multinumber*' to 'Multinumber*'
Thank you for your help!
This code has much more serious issues than you can fix by adding a
constor a typecast somewhere.The result of this code will ultimately be a crash somewhere down the line, because you’re passing a pointer to a temporary. Once you finish with line of code that calls
addElement, the pointer will be left dangling, and trying to use the object it points to will either result in nonsense (if you’re reading the object) or stack corrpution (if you’re writing to the object).The best way to redefine your code would be to change this toand call
addElementas follows:Note that I eliminated all of the extra parentheses because
*has lower precedence than[], so the parentheses aroundsetArray[i]andsetArray[i]were redundant. I think the code is more readable this way.Well really, if I can guess what’s going on here,
setArrayis the internal storage of theSetclass, so it’s type will need to be redefined fromMultinumber**toMultinumber*, in which case the call really should beEDIT Ugggh. None of the above will actually allow you to keep your polymorphism. You need to call
new Rationalsomewhere, and the only reasonable place that I can think of is:This will work without having to redefine
Set::addElement.A better solution would be to redesign the whole thing so that it doesn’t depend on polymorphism for numeric classes (because numeric classes really shouldn’t be wrapped in pointers in most normal use).