Passing an Rvalue into a copy constructor or assignment operator seems to me to be a very important thing to be able to do. For example:
int a = b+c;
or
int a;
a = b+c;
Without this it would be hard to do math calculations.
Yet I am unable to do this with a class. Here's my code
#include <iostream>
using namespace std;
struct node{
public:
node(int n){
node* ptr = this;
data = 0;
for (int t=0; t<n-1; t++){
ptr -> next = new node(1);
ptr = ptr -> next;
ptr -> data = 0;
}
ptr -> next = NULL;
}
node(node &obj){
node* ptr = this;
node* optr = &obj;
while (true){
ptr -> data = optr -> data;
optr = optr -> next;
if (optr == NULL) break;
ptr -> next = new node(1);
ptr = ptr -> next;
}
}
void operator=(node &obj){
delete next;
node* ptr = this;
node* optr = &obj;
while (true){
ptr -> data = optr -> data;
optr = optr -> next;
if (optr == NULL) break;
ptr -> next = new node(1);
ptr = ptr -> next;
}
}
~node(){
if (next != NULL) delete next;
}
private:
double data;
node* next;
};
node func1(){
node a(1);
return a;
}
void func2(node a){
node b(1);
b = func1();
}
int main(){
node v(3);
func1();
func2(v);
}
I am given this compiling error:
expects an l-value for 1st argument
how can I write a copy constructor and assignment operator that take r-values as well as l-values?
Thanks for the help