Why is this happening? operator = and copy constructor

I have the following classes:

class CRectangle
{
    CRectangle(string color);
    CRectangle(CRectangle &origin);
    /* Some more code */
};

      

and the other:

class CPlane
{
    /* Some more code */
    CRectangle boundingBox();
};

      

Why can I do this?

CRectangle rectangle1;
CRectangle rectangle2=rectangle1;
CRectangle rectangle3(rectangle1); //Copy constructor.

      

But I cannot do this:

CPlane plane;
CRectangle rectangle4=plane.boundingBox();
CRectangle rectangle5(plane.boundingBox()); //Copy constructor.

      

If I need the latter to work, how can I do it? I suppose it might have something to do with the operator =

, but I don't know for sure.

Edit: fix the copy constructor. the error is still there.

+3


source to share


2 answers


You cannot bind r values ​​to a referenced link const

.

<
CRectangle rectangle3(rectangle1);

      

Here rectangle1

is not an const

lvalue, so fine.

CRectangle rectangle5(plane.boundingBox());

      



plane.boundingBox()

is a pure rvalue (prvalue), so CRectangle&

it cannot be bound to it.

Instead, declare that your copy constructor accepts a reference const

:

CRectangle(CRectangle const&);

      

Or additionally declare a move constructor (if desired).

+3


source


Your compiler's first syntax is to query the copy constructor for infinite recursion.

It should be: -

CRectangle(const CRectangle& origin);

      



Secondly, both calls must work correctly as both are calls to copy constrcutor.

CRectangle rectangle4=plane.boundingBox();
CRectangle rectangle5(plane.boundingBox()); 

      

+5


source







All Articles