Home > Software design >  Can a copy constructor have a non-const lvalue parameter?
Can a copy constructor have a non-const lvalue parameter?

Time:01-15

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?

CodePudding user response:

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.

CodePudding user response:

The answer to the question in the title is: yes, the copy-constructor can have a non-const argument. From the C 20 draft

11.4.4.2 Copy/move constructors [class.copy.ctor]

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments

  •  Tags:  
  • Related