Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The + operator, difference between class types and built-in types?

I'm new to C++. The book I read tells me that if the plus (+) operator has been overloaded for some class object, say, the string class, to make this problem more concrete.

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string s1("abc");
    string s2("def");

    string s3("def");

    cout<<(s1+s2=s3)<<endl;

    int x=1;
    int y=2
    int z=3;
    cout<<(x+y=z)<<endl;

    return 0;
}

As you may expect, the first cout statement is correct while the second is wrong. The compiler complaints x+y is not a modifiable lvalue. My question is why the + operator returns a modifiable lvalue for string objects but not for int?

like image 859
James Fan Avatar asked Aug 14 '15 12:08

James Fan


Video Answer


2 Answers

It does not return a modifiable lvalue for string. It returns a temporary object, and s1+s2 and x+y are both rvalues.

However, objects of class type may have overloaded operator=, which string does. You are allowed to call member functions on rvalues.

The difference between the two cases is in = (not +)

like image 137
M.M Avatar answered Oct 10 '22 02:10

M.M


For std::string, s1 + s2 = s3 is in fact:

(operator+(s1, s2)).operator =(s3)

s1 + s2 returns a rvalue

Member methods can be applied to temporary also.
Since C++11, we have the lvalue/rvalue qualifier for method,
so you may forbid o1 + o2 = o3 for your custom type with:

struct Object
{
    Object& operator =(const Object& rhs) & ; // Note the & here
};

so Object::operator = can only be applied to lvalue.

like image 28
Jarod42 Avatar answered Oct 10 '22 02:10

Jarod42