Search code examples
c++copy-constructor

Can a copy constructor have a non-const lvalue parameter?


class Complex{
    int x,y;
    
    public:
    
    void setdata(int x,int y)
    {
        this->x=x;this->y=y;
    }
    Complex add(Complex &c)
    {
        Complex temp;
        temp.x=this->x + c.x;
        temp.y=this->y + c.y;
        return temp; 
    }
    Complex(Complex &c) // copy constructor
    {
        x=c.x; y=c.y;
    }
    Complex() // Simple default constructor
    {

    }
    void showdata()
    {cout<< this->x <<" "<< this->y;}
};

int main()
{
    Complex c1; c1.setdata(3,4);
    Complex c2=c1; 
    Complex c3 = c1.add(c2);
    //c3.showdata();
    cout<<"\n"<<Complex::v;
    return 0;
}

Complex c2=c1; This is fine with compiler. while Complex c3 = c1.add(c2); creates errors namely:

  • class Complex has no suitable copy constructor.
  • cannot bind non-const lvalue reference of type Complex & to an rvalue of type Complex.

Is this related to memory being released after the temp variable is destroyed or something else as i am not able to understand the errors prescribed by Compiler as mentioned above?


Solution

  • The problem is that the add member function returns an rvalue expression of type Complex and you're trying to bind a non-const lvalue reference Complex& to that rvalue.

    You can solve this error by replacing Complex(Complex &c) with:

    Complex(const Complex &c) //const added here
    

    Note the const added in the above statement. Now, the parameter of the copy constructor is a reference to const Complex which can be bound to an rvalue.