Reputation: 13
When I studied const reference type in C++, I learned returning reference type make use local variable in main function, so I tested how returned normal struct type work in lvalue. so I expected this source won't compile, but it compiled well... :( so I have two question
"Is returned struct variable?, why this code compiled well?"
"if returned struct is not variable, why this code compiled?, I assumed that returned value is rvalue.."
#include<iostream>
#include<cstring>
using namespace std;
struct travel_time
{
int hour;
int min;
};
travel_time sumTime(travel_time, travel_time);
int main(void)
{
travel_time p1, p2,sum;
cin >> p1.hour >> p1.min;
cin >> p2.hour >> p2.min;
sum=sumTime(p1, p2);
cout << sum.hour << "hour " << sum.min<<"min";
sumTime(p1, p2) = p1; //********** why it works? **********
return 0;
}
travel_time sumTime(travel_time t1, travel_time t2)
{
travel_time sum;
sum.hour = t1.hour + t2.hour+(t1.min+t2.min)/60;
sum.min = (t1.min + t2.min) % 60;
return sum;
}
Upvotes: 0
Views: 335
Reputation: 96959
Is returned struct variable?, why this code compiled well?
This doesn't make much sense.
travel_time sum;
is a variable. When you call sumTime
, you return a copy of this variable, and that copy itself isn't a variable. So the answer is no, the result of calling the function isn't a variable.
I have a feeling what you really wanted to ask is if the result of calling the function is an lvalue - it's not, the result is an rvalue (more specifically, prvalue).
if returned struct is not variable, why this code compiled?, I assumed that returned value is rvalue..
This again makes no sense, unless I replace "variable" with "lvalue".
In C++, you can assign to rvalues of class types (but not of privitive types such as int
). Note that struct travel_time
is a class, despite using the word "struct". Strictly speaking, there are no structures in C++, only classes.
There are ways to prevent this kind of assignment for your class, but you didn't do that.
Upvotes: 1