Ok, So I’ve googled this problem and I have searched stack overflow but I can’t seem to find a good answer. So, I am asking the question on here that is particular to my problem. If it is an easy answer, please be nice, I am new to the language. Here is my problem:
I am trying to write a method for a C++ class that is overloading an operator. I want to return a copy of the instance modified but not the instance itself. For ease of example, I’ll use a BigInt class to demonstrate the problem that I am having.
If I had the following code:
const BigInt & operator+() const //returns a positive of the number
{
BigInt returnValue = *this; //this is where I THINK the problem is
returnValue.makepositve(); //for examples sake
return returnValue;
}
I get the error that the return value may have been created on the stack. I know that this means that I have to create the object on the heap and return the reference. But If I were to change the 3rd line to something like:
BigInt & returnValue = *this;
I get an error telling me that the syntax is not right. I’m not really sure what to do, any help is much appreciated!
The problem is in your function signature. You really do have to return the entire object and not just a reference.
Your function will look like this