Polynomial operator + (const Polynomial& p);
//Adds existing Polynomial to p, returning the result
So because we can't change the value of a const, is there a way to make a copy of this p to allow me to access the functions of p?
Sorry guys at work and quite display the entire program, but in Poly.H in the private field it reads: private: List < Term > poly
So in PolyTest.cpp
If I need two polynomials p_add = poly1 + poly2
I need to write the function in the operator+ to add like terms. Hope this is helpful.
If you need to make a copy then just copy it in the function
Polynomial operator + (const Polynomial& p);
{
Polynomial copy = p;
// do stuff
}
Now just because p is const doesn't mean you cannot use its members/functions. A typical operator+ would look like
Something operator + (const Something& s);
{
return Something(this->some_memeber + s.some_memeber,
this->another_memeber + s.another_memeber);
}
If you need a copy inside operator+, the most straightforward way of doing it is to pass p by (const) value:
Polynomial operator+ (Polynomial p);
Now p is a copy of the object you passed in that you can mess up with inside operator+. Of course if you pass by const value like
Polynomial operator+(const Polynomial p);
then the copy itself will be const, so you will be able to access only its const member functions.
As mentioned in the comments, sometimes passing by const reference and making sure that you only access the const member function is what you actually need, since you avoid the additional copy. However there are situations when a copy is necessary (most likely not here), such as when implementing the famous copy-and-swap idiom, in which case passing the object by value is the way to go, and the least verbose way of achieving the desired effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With