0

I am new to c++. Here is my problem:

I have created a class in c++ that overloads operator+ and returns an object of the same class

#include <iostream>
using namespace std;

class A{
    private:
    int value;

    public:
    A(int val){
        this->value = val;
    }

    A operator+(A a2){
        A a(this->value + a2.value);
        return a;
    }

    friend ostream& operator<<(ostream& os, const A& a){
        return os<<a.value;
    }
};

int main(){
    A a1 = {1};
    A a2 = {2};
    A a3 = {3};

    cout << a1 + a2 + a3 << " ";
    cout << a1 + (a2+a3) << endl;

    return 0;
}

This works totally fine and prints 6 6 on the terminal. But this uses deep copy while using + operator and I want to avoid it.

I tried changing A operator+(A a2){ to A operator+(A& a2){ so that values are passed by reference. This works for a+b+c but for a+(b+c) it fails and gives a long error. The following seemed important:

error: no match for ‘operator+’ (operand types are ‘A’ and ‘A’)
   30 |     cout << a1 + (a2+a3) << endl;
      |             ~~ ^ ~~~~~~~
      |             |       |
      |             A       A

So my question is: Is there a way to achieve the syntax a+(b+c) without deep copy and how? It is mandatory for me to create a class, and support that syntax. I can't use const A&.

I am using c++14 and ubuntu-20.04

Abhinav
  • 1
  • 2
  • 2
    [This question](https://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object) is a bit long, but the gist of the problem is that `A&` will only take a named lvalue. If you change it to `const A&`, you promise that you won't change the variable, and that also enables the function to accept rvalues like `(a2 + a3)`. – Nathan Pierson Apr 13 '22 at 04:18
  • Sorry, I forgot to mention that i cannot use const. I need to change the variable. Let me edit. Is it still possible? – Abhinav Apr 13 '22 at 04:25
  • 3
    Why do you need to change the variable? – Nathan Pierson Apr 13 '22 at 04:42
  • "Deep" and "shallow" copying does not mean what you think it means. – molbdnilo Apr 13 '22 at 06:35
  • _I can't use const A&._ Either you use `operator+(A)` and live with the extra copy for the argument or you use `operator+(const A&)` (which is completely idiomatic) and prevent the extra copy. The restriction to prohibit `const A&` is hard to understand. Please, explain why. – Scheff's Cat Apr 13 '22 at 07:00
  • An idiomatic + operator doesn't change any of its (two) arguments. Hence, it's fully reasonable to provide a const reference for the 2nd argument as well as to remark the operator definition as const (which will affect `this` - the implicit first argument). In your exposed code, there is no indication that any of them isn't possible. – Scheff's Cat Apr 13 '22 at 07:10
  • My problem is now solved. It seems that I can use const. I am really sorry for the inconvenience. – Abhinav Apr 14 '22 at 17:11

0 Answers0