Digesh Patel
Digesh Patel

Reputation: 23

Overloading assignment and plus operator

#include<iostream>
using namespace std;

class test
{
    int i;
    string s;

    public:
    test(){}

    test(int a,string b)
    {
        i=a;
        s=b;
    }

    void operator = (test &temp)
    {
        cout<<"In assignment operator"<<endl;
        i=temp.i;
        s=temp.s;
    }

    test  operator + (test &temp)
    {
        test newobj;
        newobj.i=i+temp.i;
        newobj.s=s+" "+temp.s;
        return newobj;
    }
};

main()
{
    test t1(5,"ABC");
    test t2;
    t2=t1;
    test t3;
    t3=t1+t2;
}

Question : t3=t1+t2 gives me an error. I want to overload both = and + operators and use them as shown above. Where am I wrong ? I want to explicitly define one assignment operator overload even though one is provided by compiler.

error : invalid initialization of non-const reference of type ‘test&’ from an rvalue of type ‘testt3=t1+t2;

initializing argument 1 of ‘void test::operator=(test&)void operator = (test &temp)

Upvotes: 2

Views: 481

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

t1+t2 returns a temporary test, which can't be bound to reference to non-const (i.e. test &), that's why t3=t1+t2; fails. On the other hand, temporary could be bound to reference to const (i.e. const test&). So you can change the parameter type to const test&, e.g.

void operator = (const test &temp)
{
    cout<<"In assignment operator"<<endl;
    i=temp.i;
    s=temp.s;
}

BTW1: It's better to do the same thing with operator+.

BTW2: The conventional signature (and implementation) of operator= is:

test& operator= (const test& temp)
{
    cout<<"In assignment operator"<<endl;
    i = temp.i;
    s = temp.s;
    return *this;
}

Upvotes: 1

Related Questions