charan kamma
charan kamma

Reputation: 37

copy constructor and overloaded '=' operator not working

The copy constructor and overloaded '=' operator are not being called when assigned with result of sum of two class objects. There are working properly when initialized and assigned with single object. the error says "no match for ‘operator=’ (operand types are ‘comp’ and ‘comp’)". Important code snippets are

class comp
{
    int a,b;
public:
    comp()
{
    a=b=1;
}
    comp(int,int);
    comp(comp &);
    comp operator+(comp &);
    operator int();
    void show()
    {
        cout<<"a= "<<a<<"b= "<<b<<endl;
    }
    comp& operator=(comp &);
    friend ostream &operator<<(ostream &out, comp &c);
};


    comp::comp(comp & c)//copy constructor
    {
        a=c.a,b=c.b;
        cout<<"copy constructor called"<<endl;
    }
    comp comp::operator+(comp & c1)// overloaded '+' opreator
    {
        comp c;
        c.a=a+c1.a;
        c.b=b+c1.b;
        return c;
    }
    comp & comp::operator =(comp & c)// I tried with return type as void also
    {
         cout<<"in operator ="<<endl;
        a=c.a,b=c.b;
        return *this;
    }
int main()
{
    comp c1,c2(2,3),c3;
    c3=c2+c1;
    cout<<c3;
    comp c4=c3+c1;
    cout<<c4;
    int i=c4;
    cout<<i;
    return 0;
}

Upvotes: 1

Views: 214

Answers (2)

DanielGut
DanielGut

Reputation: 1

By default some copy operations are optimized. To make sure that no copy optimization is used you should use proper compiler flag. For gcc try to use: -no-eligible-constructors

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409166

Lets take this line

comp c4=c3+c1;

The c3+c1 operation returns a temporary object. However, non-constant references can't bind to temporary objects, and your copy-constructor takes its argument as a non-constant reference.

The fix is simple, change the copy-constructor and copy-assignment operator to take their arguments as constant references instead, e.g.

comp(const comp& c);

Note that using a non-constant reference argument in e.g. a copy-constructor still makes it possible to use it, you just have to pass actual non-temporary objects to it, like

comp c1;
comp c2 = c1;  // Should work with non-constant reference

Upvotes: 2

Related Questions