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